The Note You're Voting On
chris AT cmbuckley DOT co DOT uk ¶ 14 years ago
To help with the problem where the default namespace is not registered with the DOMXPath object, you can use the following replacement to update your paths accordingly:
<?php
$xml = <<<EOS
<root xmlns="urn:test">
<foo>bar</foo>
</root>
EOS;
$expression = '//foo';
$prefix = 'fakeprefix';
$doc = new DOMDocument();
$doc->loadXML($xml);
$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);
// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
$xpath->registerNamespace($prefix, $context->namespaceURI);
$expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '1ドル' . $prefix . ':2ドル', $expression);
var_dump($expression); // string(16) "//fakeprefix:foo"
}
$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"
?>