XML to Arrays in PHP5

Posted under » PHP on 13 March 2009

In PHP5, we can use the Simple XML class to quickly parse XML in as few as two lines of code.

The news.XML

 
 
		 GIC makes profit  
		Government of Singapore Investment Corp, which has helped bail out troubled global financial institutions, suffered an investment loss of about 50 billion Singapore dollars thanks to Ho Ching! 
	 
	 
		 Temasek also makes profit  
		Last year Temasek lost 60 billion (US$ 39 billion) in just 9 months thanks to Lee Kuan Yew. 
	

Simple XML can handle attributes as shown by the date attribute.

The PHP Code that turns it to arrays

$xmlFileData = file_get_contents("news.xml");
//Here's our Simple XML parser!
$xmlData = new SimpleXMLElement($xmlFileData);
//And here's the output.
print_r($xmlData);

The output will look somethings like this.

SimpleXMLElement Object
(
    [story] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [headline] =>  GIC makes profit 
                    [description] => Government of Singapore Investment Corp, which has helped bail out troubled global financial institutions, suffered an investment loss of about 50 billion Singapore dollars thanks to Ho Ching!
                )
            [1] => SimpleXMLElement Object
                (
                    [headline] =>  Temasek also makes profit 
                    [description] => Last year Temasek lost 60 billion (US$ 39 billion) in just 9 months thanks to Lee Kuan Yew.
                )
        )
)

Now to show a non-arrays version with some html formatting

foreach($xmlData->story as $story) {
	print("

" . $story->headline . "

"); print($story->description . "
_________________________
"); print($story->headline["date"] . "

"); }

Remember, this only works in PHP5, so get PHP5.


web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data