Tuesday 14 May 2013

Parse XML in PHP By example [Solved]


The DOM XML parser functions are part of the Core PHP. To parse xml data you need not to install anythings. there are different functions available in php that can help you to add, update, delete and list the xml data.


following are examples to list the XML data into objects.
Suppose you having following XML, to Parse
http://www.web-technology-experts-notes.in/rss.xml?redirect=false&start-index=1&max-results=2

Example 1
$fileData = file_get_contents('http://www.web-technology-experts-notes.in/rss.xml?redirect=false&start-index=1&max-results=2');
$output = simplexml_load_string($fileData);
print_r($output);

Example 2
$fileData = file_get_contents('http://php-tutorial-php.blogspot.in/rss.xml?redirect=false&start-index=1&max-results=2');
$domxml = DOMDocument::loadXML($fileData);
$output= simplexml_import_dom($domxml);
print_r($output);

Example 3
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.web-technology-experts-notes.in/rss.xml?redirect=false&start-index=1&max-results=2');
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
  {  
  print $item->nodeName . " = " . $item->nodeValue . "\n";  
  }

}

Example 4
$fileData = file_get_contents('http://www.web-technology-experts-notes.in/rss.xml?redirect=false&start-index=1&max-results=2');
$output = new SimpleXMLElement($fileData);
print_r($output);