# Create an Image from XML Data


By Ben Ramsey

Published on May 19, 2006


I had some time to kill and a silly problem to solve, which means here's some more [SimpleXML](http://php.net/SimpleXML) fun for you:

## The Problem

It's not really a "problem," but [FeedBurner's](http://en.wikipedia.org/wiki/FeedBurner) FeedCount™  image is a rigid 88 pixels wide, and I wanted to include it on my [homepage](http://benramsey.com) 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](http://www.feedburner.com/fb/a/developers/awapi)," which is a [RESTful](http://en.wikipedia.org/wiki/Representational_state_transfer) interface to retrieve (as XML data) the same exact information displayed in the FeedCount™ 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](http://php.net/image) 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!

```php
// 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, 0x00, 0x66, 0xCC);
imagestring($img, 2, $xpos, 2, $readers, $color);

// Save the image
imagegif($img, 'feedburner-readers.gif');
```

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 `x` coordinate.


