PHP

Parsing XML With DOMXML And PHP

Extensible Mark-up Language (XML) has just about made its impression everywhere: B2B, B2C, as a replacement for .INI files, to aid with data abstraction and transportation, etc. In this article Mitchell shows us how to use the DOMXML library to parse and extract data from both local and remote XML files with PHP.

To extract the contents of the <url> node, we would use the following PHP code:

<?php

$theXML = "<?xml version='1.0'?>";

$theXML .= " <website><url>";

$theXML .= " http://www.devarticles.com";

$theXML .= " </url></website>";

$xmlDoc = xmldoc($theXML);

$root = $xmlDoc->root();

$node = array_shift($root->children());

echo $node->content;

?>

We start by creating a string that contains our XML. The xmldoc() function creates an object that contains our hierarchically structured and validated XML data. If our XML was not valid, then the xmldoc() function would spit an error, like this:

One of the great things about using the DOMXML parser is that you can just as easily load a local or remote file, using the xmldocfile() function instead:

$xmlDoc = xmldocfile("/htdocs/xml/sample.xml");

OR

$xmlDoc = xmldocfile("http://www.mysite.com/sample.xml");

All XML documents have a single root element, which is the starting point of the documents content. In our example, it's the <website> element. We retrieve the root element with the root() function, like this:

$root = $xmlDoc->root();

Once we have access to the root element, we use its children() function to return a list of its child nodes as an associative array. The array_shift() function pops the first item off the array and returns it as an associative array. Its "content" key/value pair will contain the URL that we're after, and we use the echo command to write it to the browser window: