Code sur écran d'ordinateur

PHP, DOMdocument and xPath to spar an xml file

When we have to process a very large XML, it is unfortunately not possible to use SimpleXML. Fortunately for this, we can use DOMDocument.

To do this, just load the desired file and initialize xpath on it with DOMXPath.

$document - new DOMDocument();
$document-load ($file);
$xpath - new DOMXPath ($document);

If the XML in question has a namespace, don’t forget to register it.

$xpath-registerNameSpace ('n', 'http://www.w3.org/TR/html4/');

Once this is done, we can start making our xPath queries.

        $elements - $xpath-query ('/n:movie');
        foreach ($elements as $element)
}

It is very important that in the xPath query each node has the namespace, in our example “n”

Leave a comment