Reading XML with PHP
Since webservices and RESTful services are becoming more and more popular, XML is getting a common format to exchange information. XML is easy to read and has a nice tree structure, which can be easily interpreted.
This post will show you how easy it is to read XML in PHP.

In this tutorial I’ll teach you how to read information which a simple webservice provides. The webservice I choose is Last.fm. It’s quick, fun and has a lot of features. We’ll use the Recent Tracks information of a user profile.
According to the API of Last.fm the XML which will be returned will look something like this:
<?xml version="1.0" encoding="utf-8"?> <lfm status="ok"> <recenttracks user="xgayax"> <track nowplaying="true"> <artist mbid="1bc41dff-5397-4c53-bb50-469d2c277197">The Dillinger Escape Plan</artist> <name>Party Smasher</name> <streamable>1</streamable> <mbid></mbid> <album mbid="">Ire Works</album> <url>http://www.last.fm/music/The+Dillinger+Escape+Plan/_/Party+Smasher</url> <image size="small">http://userserve-ak.last.fm/serve/34s/19117171.jpg</image> <image size="medium">http://userserve-ak.last.fm/serve/64s/19117171.jpg</image> <image size="large">http://userserve-ak.last.fm/serve/126/19117171.jpg</image> <date uts="1230497786">28 Dec 2008, 20:56</date> </track> ... </recenttracks> </lfm>
This is a part of the actual XML Last.fm gave me. We can see that is not too complicated, which is a good thing!
So what do we need to do now? First, we need that XML file in PHP. We can accomplish that by using the simplexml_load_file function in PHP (Introduced with PHP5).
It only needs the URI to the XML file and it will convert the string into an XML object. Pretty neat.
Create a new PHP file and place this code somewhere:
$completeurl = "http://ws.audioscrobbler.com/2.0/?method=&user=xgayax" . "&api_key=b25b959554ed76058ac220b7b2e0a026"; $xml = simplexml_load_file($completeurl);
This will load the given file into an object. The url can be adjusted to your needs, preferably the API key since I borrowed it from the Last.fm site.
All what’s left for us to do is to loop through the given object.
Take a look at the following code:
$tracks = $xml->recenttracks->track;
for ($i = 0; $i < 3; $i++) {
$nowplaying = $tracks[$i]->attributes()->nowplaying;
$trackname = $tracks[$i]->name;
$artist = $tracks[$i]->artist;
$url = $tracks[$i]->url;
$date = $tracks[$i]->date;
$img = $tracks[$i]->children();
$img = $img->image[0];
echo "<a href='" . $url . "' target='TOP'>";
if ($nowplaying == "true") {
echo "Now playing: ";
}
echo "<img src='" . $img . "' alt='album' />
$artist . " - " . $trackname . " @ " . $date . "
</a>
";
}
To understand what is happening, I’ll explain some of the actions I did to get the right information.
Going through the XML tree is easy. $xml will refer to the root element, which is <lfm> in this case. From this element we can navigate through the XML tree.
If you want: <lfm><recenttracks><track> you’ll get $xml->recenttracks->track in PHP. And because recenttracks contains multiple tracks an array will be given.
The size of the loop is limited to 3, you can however replace this with sizeof($tracks) is you please.
Just like explained above, getting the information inside a tag is done like this: $tracks[$i]->tagname. You’ll get the text which is inside (if it contains text, or else you’ll get an object or an empty string.)
To read attribute information, you need to use the attributes() method. Like I did in this line: $tracks[$i]->attributes()->nowplaying. If the attribute doesn’t exist you’ll get an empty string.
I hope this gets you into reading XML’s using PHP. It is easy and takes little time to learn.
I’ve used XML reading for serveral purposes now like synchronizing information with a database and displaying upcoming event information.
The power of XML is now in your hands.
Gaya Kessler is a 22 year old web developer writing about all kind of things. He’s the owner of Gaya Design. You can also catch him on twitter.


This is the most useful tutorial on PHP parsing XML I’ve ever seen. Nice and straight to the point.
Thanks for the compliment Ethan.
My aim is to make articles as easy to understand as possible. I could go into ALL the details, but that wouldn’t work.
Yeah I learned about that a few months ago. Wish I knew about it the second 5 came out because it made life so easy.
That’s half the battle – finding out what these functions are called, heheh.
Nice going! Will definitely be making use of it.
Btw, any functions around to re-encode a object as XML? Or is that the sole province of JSON?
~ Wogan
Thanks for the comments guys!
@Wogan:
There is a way to output the XML again as a string: $xml->asXML(); will do this with the object we just made. Pretty easy and amazingly strong when adjusting the object!
Just as an additional note, something I worked out for myself whilst processing xml responses from the basecamp api:
If an xml element name contains reserved characters (in this case, a hyphen), you need to add curly braces around the item name e.g.
$lists = simplexml_load_string($response->data);
foreach($lists->{todo-list} as $list){
$this->TodosComplete = $this->TodosComplete + $list->{completed-count};
$this->TodosIncomplete = $this->TodosIncomplete + $list->{uncompleted-count};
}
How we pass the xml in php 4.3.9
There are some SimpleXML classes available for PHP < 5, most of them are quite good copies.
Decent tutorial for beginners; might want to clean up your code next time though. ;)
You should also do this:
$feed = ‘http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=YourName&api_key=’;
$local = ‘YourName.xml’;
if( (!file_exists($local)) || (time() – filemtime($local) > 120) )
{
$contents = file_get_contents($feed);
$fp = fopen($local, “w”);
fwrite($fp, $contents);
fclose($fp);
}
$xml = simplexml_load_file($local);
Makes a local cache of the XML file every two minutes. This really improves the page load time.
An alternative (and much more versatile) method of managing and parsing XML data is using the DOMDocument class ( The class details can be found at http://us3.php.net/manual/en/class.domdocument.php ).
For simple XML work, the simplexml method as the name “simplexml” implies, but it does not allow for any actual manipulation of the XML DOM (upon which many advanced interactions between PHP and XML rely) and it actually makes working with XML namespaces (like the Dublin Core, API-specific Namespaces, and any other custom namespaces that a data provider might use).
Hi
i used this script .but there is error
Fatal error: Call to a member function attributes() on a non-object in D:\xampp\htdocs\xml.php on line 9
I get an error with this code. How disappointing! :-(
Parse error: syntax error, unexpected ‘@’, expecting ‘,’ or ‘;’
Too complicated!
Shouldn’t have relied on an example with Last.fm. Use a simpler XML file.
Well actually after diggin around at how to do this for a few hours, stumbling upon this made it all ‘click’.
If you want an example of an easier XML file try w3schools, this one was well written.
Thanks for this it sent me FLYING over the hump.
Wow, this was a great tutorial. I tried using DOM objects and all sorts of “simple” php xml functions before your tutorial that all didn’t work. this was exactly what I needed! THANK YOU! :)
Thank you for fueling my coding… This tutorial finally gave me an insight.
Hey,
Hopefully someone can help me with this. I’ve managed to parse some XML using PHP to create a search engine using the artists.getEvents – but I would like to limit this information to my city. Adding a location parameter to artists.getEvents isn’t possible – does anyone have any ideas?
Thanks!
How do you adapt this example for a service that sends the XML (rather than me requesting it)?
Service send might be trigger by something like a messsage or post sent to server. Server sends alert in XML to me.
Thnaks in advance for your help.
@George, depending on how you get the XML, you just point the simplexml_load_file() to that file.
It’s was a really useful post. Thank you!
Thanks!! I even happened to be working with Last.fm’s API, so this was perfect. It also showed me that it’s much simpler to use simplexml_load_file instead of cULR, which I was using before.
Hello everyone, I included these code but not working, can you help me.
i need help in that:
i use function simplexml_load_file();
when i wrote filename in brackets it work fine, but when i wrote url with http for example
“http://ws.audioscrobbler.com/2.0/?method=&user=xgayax” – it does not work
what can i do?
nice, clean and simple.
Thanks.
I love this tutorial.. this is the best one I found , related to simpleXML :)