PHP 8.5.0 Alpha 4 available for testing

Voting

: six minus six?
(Example: nine)

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>"

?>

<< Back to user notes page

To Top