My work for the Lilliput CMS has lead to some interesting new findings about PHP 5’s new DOM functions, particularly the XPath part of it. Whilst working on the templating structure for Lilliput I couldn’t get the DOM XPath queries to work on the file at hand, a normal XHTML 1.0 Strict document. With an external tool called XPath Explorer (XPE) every query evaluated correctly but as soon as I tried the same XPath expression in PHP it failed. After searching long and hard I came across a code snippet that contained the solution namely to explicitly declare the xhtml namespace for the DOM document you’re working on:
<?php $templateFile = 'template/lilliput/index.xhtml'; $dom = new DomDocument('1.0', 'utf-8'); $returnValue = $dom->load($templateFile); $xpath = new DOMXPath($dom); $xpath->registerNamespace("xhtml", "http://www.w3.org/1999/xhtml"); $nodelist = $xpath->query('//xhtml:div[@id="content"]'); $noderesult = $nodelist->item(0); ?>
After this no problems any more but very strange that this isn’t mentioned in the PHP DOM documentation anywhere. Even stranger that my user contributed note on this on the XPath query function manual page doesn’t seem to have been accepted. Hopefully somebody will gain some help from this blog entry.