Warning: DOMXPath::query() does not accept the syntax

45 Views Asked by At

I'm trying to extract a DOMDocument in PHP with the help of DOMXPath. With the website http://xpather.com/ I tried to find the correct query for my needs.

The query is the following:

/*/* except /*/*[@id='test']

What I try to achieve: In a DOM document, I need only the content of a container with the ID test in this case. Nothing else. In XPather the result looks good. No errors. Everything works as expected. But when I try this in my PHP application, I get the error from the title: DOMXPath::query(): Invalid expression

My code:

$domDocument = $this->domParser->loadHTML($markup);
$xpath = new \DOMXPath($domDocument);
$nlist = $xpath->query("/*/* except /*/*[@id='test']");

if ($nlist != null) {
    $node = $nlist->item(0);
    $node->parentNode->removeChild($node);
    $domDocument->saveHTML();
}

Where is the error here?

1

There are 1 best solutions below

0
On

The reason is: except is XPath 2 and DOMXPath uses XPath1. So easy :)

The correct XPath1 query is the following: "/*/*[not(@id='test')]"

Thanks @Nigel Ren for your hint :)