SimpleXML in PHP 5
       by Esherido | 2 August 2006

In an earlier tutorial you might have read, XML Parsing using PHP { Intermediate }, the full XML Parser class was used, which requires tons of lines of code and extra time. In PHP5, we can use the Simple XML class to quickly parse XML in as few as two lines of code.

Our Extensible Markup Language Text
I'm using the same text as Jubba's XML Parsing tutorials, except I might add some attributes to show you the extra power of Simple XML:


Our PHP Code
I know you're expecting a couple hundred or so lines of advanced PHP with impossible to understand comments. You're wrong, here's the two lines you need to get a Simple XML object:

Execute that on your PHP server, and you get some meaningless gibberish like the following.

To actually get data from that jumble of values, we can access it as an array with a class applied to it. Like so:

But what if you wanted the date of the story, but didn't want to have to add another node to the story array? Just add an attribute. And Simple XML can also handle attributes! So our new XML looks like:

So now we have all our news and their dates, but how do we show it to people? We can use a simple foreach loop to output everything to people.

Of course the output doesn't look very pretty, but you could write some nice CSS or something to fix that! Remember, this only works in PHP5, so get PHP5, because it's so much better than any other version of PHP!

Something along the lines of 'Cheers!'


SUPPORTERS:'s fast and reliable hosting provided by Media Temple.