One of the details we were able to parse from the XML feed was the location of the user’s Twitter avatar. We’re going to display this on our signature image, so we’ll need to make another CURL request to grab the image and store a copy of it locally. private function fetchAvatar($url, $adir) { $fname = end(explode('/', $url)); $adir = preg_match('#^(.*?)/$#i', $url) ? $adir : "{$adir}/"; $fname = $adir . $fname; if ( !file_exists($fname) ) { $img = $this->curlRequest($url); $fp = fopen($fname, 'w'); fwrite($fp, $img); fclose($fp); } $this->local_avatar = $fname; } This function is pretty basic. It uses the curlRequest function to retrieve the avatar image and write it to a local file. You’ll see a couple of really nifty PHP techniques employed in the first two lines. The first technique is a quick method of parsing the image file name from a URL. You’ll recall that URLs have several parts, all delimited by a forward slash. PHP’s explode function can create an array from a string based on a string delimiter. This very quickly creates an array of each of the URL parts. The end function then returns the last element in the array (being the file name portion of the URL). This is a quick and dirty technique for returning the end portion of a delimited string. The second technique combines a regular expression match with the ternary operator. It checks the avatar directory string for a trailing slash and returns either the path if it includes one or the path with a slash appended to it. This nice one-liner ensures that our path always contains a trailing slash. RecappingOur Twitter SignatureImage class is nearing completion. We’ve added all of the functions to retrieve a user’s Twitter feed information and copy the user’s avatar image. In the second part of this article series we’ll take a look at building and rendering the actual signature image. We’re also going to look at adding appropriate error handling and a file caching feature. The latter is important since Twitter limits the number of API requests a single IP may request in a specific amount of time. Caching will store a copy of the XML feed locally to prevent making too many requests to the API service. I’ll also be demonstrating a quick method of tracking how many impressions your image gets which is useful if you’re using your image in forum signature. And of course, I’ll show you how to actually implement the SignatureImage class. Until next time, keep coding!
blog comments powered by Disqus |
|
|
|
|
|
|
|