Create an Image From XML Data
I had some time to kill and a silly problem to solve, which means here’s some more SimpleXML fun for you:
The Problem: It’s not really a “problem,” but FeedBurner’s FeedCountTM image is a rigid 88 pixels wide, and I wanted to include it on my homepage under the “syndicate” heading, an area that I’ve defined in my template as having only 80 pixels in width. The 88 pixels were throwing things off, so I used the width attribute of the HTML
img tag to solve the problem. Unfortunately, it just squeezes the image, making the text in it appear fuzzy.
The Solution: FeedBurner conveniently provides what they call their “Awareness API,” which is a RESTful interface to retrieve (as XML data) the same exact information displayed in the FeedCountTM image. Since I wanted to maintain the same kind of image (because it’s a recognized look-and-feel for FeedBurner feeds), I simply fired up an image editing program, shuffled things around a bit until the image was a nice, clean 80 pixels wide, and saved it as the base image (shown to the right) I would use for generating an image similar to the one FeedBurner provides.
Then, I wrote a script to grab the FeedBurner data (using SimpleXML) and used PHP’s image functions to open the base image, write the FeedBurner circulation data to it, and save it to use on my site. I simply have a cron job that runs this script once a day to keep my image updated.
Here’s the code. Enjoy!
// Get the XML data from Feedburner
$sxe = new SimpleXMLElement(‘http://api.feedburner.com/awareness/1.0/GetFeedData?uri=ramsey’, NULL, TRUE);
$readers = (string) $sxe→feed→entry[‘circulation’];
// make sure it’s a number
$readers = is_numeric($readers) ? $readers : ‘0’;
// 39 is the base position; 6 the width of each char
$xpos = 39 – (strlen($readers) * 6);
// Create the image from the base image
$img = imagecreatefromgif(‘feedburner-base.gif’);
$color = imagecolorallocate($img, 0×00, 0×66, 0xCC);
imagestring($img, 2, $xpos, 2, $readers, $color);
// Save the image
This is more or less same way in which QR Codes are generated.
Note that I determined the numbers used in lining up the text in the image by trial-and-error. I played around with it a bit to get things right. The
$xpos variable is my attempt to right-align the text because you can only specify the left edge of the text with the