Back to blog

PHP to get twitter infos and avatar

I’ve just updated the Mini Bot Php Class with an improved version of the twitterInfo function, here is the code…

I’ve just updated the Mini Bot Php Class with an improved version of the twitterInfo function, here is the code of the new function, I’ve added the avatar image url:

/* this function is part of the Mini Bot Class */

	//
	// get twitter infos from nickname
	// and get avatar url
	public function twitterInfo($nick) {
		$user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
		$ch = curl_init();    // initialize curl handle
		curl_setopt($ch, CURLOPT_URL, "http://twitter.com/$nick"); // set url to post to
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);              // Fail on errors
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // allow redirects
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
		curl_setopt($ch, CURLOPT_PORT, 80);            //Set the port number
		curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
		curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
		$document = curl_exec($ch);
		preg_match_all('#<div class="stats">(.*)</div>#Uis', $document, $stats);
		preg_match_all('#<span[^>]*?>(.*)</span>#Uis', $stats[1][0], $spans);
		$o = array();
		for ($i=0;$i<count($spans[0]);$i++) {
			if ($this->attr($spans[0][$i],"id")=="following_count") $o['following'] = $spans[1][$i];
			if ($this->attr($spans[0][$i],"id")=="follower_count") $o['follower'] = $spans[1][$i];
			if ($this->attr($spans[0][$i],"id")=="lists_count") $o['lists'] = $spans[1][$i];
		}
		$o['avatar'] = "";
		preg_match_all('#<img [^>]*?>#Uis', $document, $t);
		for ($i=0;$i<count($t[0]);$i++) if (attr($t[0][$i],"id")=="profile-image") $o['avatar'] = attr($t[0][$i],"src");
		return $o;	
	}

Canonical URL