Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Oct 5, 2013

How to parse and process XML in PHP

Still a lot of WebServices and RESTful services provides output as XML.

Reading XML in PHP is very easy. This post will show you the easiest way to read XML in PHP. You will learn how to read information which a webservice provides as XML.

Lets take an simple example of Flickr photos search API that return XML as output.

The XML looks like this

PHP code
//XML source URL
$xmlUrl = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOUR_API_KEY&tags=love&format=rest';

//It will return you and SimpleXMLObject
$xmlObj = simplexml_load_file($xmlUrl);
print_r($xmlObj);

Output of above code will look like this

Reading XML string?

If you have XML String in your code you can use this code.

//Reading the XML source URL to get XML string
$xmlString = file_get_content('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOUR_API_KEY&tags=love&format=rest');

//It will return you and SimpleXMLObject
$xmlObj = simplexml_load_string($xmlString);
print_r($xmlObj);


How to deal with SimpleXMLElement Object
 
Processing the SimpleXMLElement is easy. But you can make it easier by converting SimpleXMLElement Object to Php Array.


Labels: , , ,




By :