The first programming step to creating our image is pretty obvious. We need to retrieve the Twitter feed and parse the information that we need. To do that, we’ll create a function called fetchUserInfo. We’ll also create a function called curlRequest that will act as a wrapper function for the CURL process that will retrieve the external site content. private function fetchUserInfo($name) { $url = "http://twitter.com/statuses/user_timeline/{$name}.xml?count=1"; $xml = $this->curlRequest($url); if ($xml === false) { // User feed unavailable. } $statuses = new SimpleXMLElement($xml); if (!$statuses || !$statuses->status) { // Invalid user channel. } foreach ($statuses->status as $status) { $this->status_text = (string) $status->text; $this->profile_image = (string) $status->user->profile_image_url; $this->screen_name = (string) $status->user->screen_name; break; } } This function is much simpler than it looks initially. It accepts a string containing the Twitter screen name. That name is used to create a feed URL as described earlier, and then a request is made using $this->curlRequest (to be created) that returns the XML contents of the Twitter feed. Next, we use the SimpleXMLElement class to parse the XML content and assign the information we need to class-level variables. Of course, this is all of little worth if we don’t add the curlRequest function that performs the request for the feed. private function curlRequest($url) { if (!extension_loaded('curl')) { // PHP extension CURL is not loaded. } $curl = curl_init($url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); if (curl_errno($curl) !== 0 || curl_getinfo($curl, CURLINFO_HTTP_CODE) !== 200) { $result === false; } curl_close($curl); return $result; } If you’ve used CURL in the past, this function will look pretty basic. First it checks that CURL is actually available, and then makes a request to the URL provided. It returns the response from that request or a Boolean false if there’s an error. Throughout these code samples, I’ve added error checking but left only comments as to the error. We’ll be going back later to add proper error handling. Now we can take advantage of our function by adding a call to $this->fetchUserInfo to the class’s constructor. While we’re at it, we’ll add a call to $this->fetchAvatar, which is the function we’ll be creating next to load the user’s avatar image. The constructor now looks like this. public function __construct($name, $bg_image, $adir) { $this->fetchUserInfo(strtolower($name)); $this->fetchAvatar($this->profile_image, $adir); } You may have also noticed that I’m using the strtolower function to force the user name to be lower-case. This aids in feed caching, which is a feature we will be adding later. For now, it just adds uniformity when creating the feed URLs.
blog comments powered by Disqus |
|
|
|
|
|
|
|