HomePHP Page 4 - Dynamic Twitter Signature Images with PHP
Grabbing the avatar image - PHP
Twitter is the latest and greatest craze in social networking sites. As such, many developers and businesses are using it as a marketing technique. Today we’re going to come up with a method for creating a dynamic signature image for forum posts and emails that will automatically load your Twitter feed and display your latest Twitter status. We’ll be using PHP to grab the content along with GD2 support to create the image.
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.
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.
Our 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!