Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate xpath syntax correctness in php

I have a given xpath with no xml document to try and test it against, but I still have to make sure the xpath is correctly formatted.

Two examples are as follows:

CORRECT SYNTAX: '//BuyerCookie/child/grandchild'

INCORRECT SYNTAX: "/foo/bar/@baz/@boy"

I need to check whether a correct or an incorrect xpath string has been passed in. Any suggestions?

Basically the exta same questions as this one:

XPath expression syntax validation

But a PHP solution.

like image 826
Pro-grammar Avatar asked Jul 02 '26 02:07

Pro-grammar


1 Answers

It looks like if you use DOMXPATH::query($xpath) with your XPath selector to test, it will return FALSE if the XPath is not valid.

So, I would try:

$doc = new DOMDocument;
$xpath = new DOMXPath($doc);

// this one is good
$str="//a//li/div[@class='foo']";
assert($xpath->query($str) !== false);

// this one is bad
$str="//a/@@bob/uncle";
assert(@$xpath->query($str) === false);

See also: https://www.php.net/manual/en/domxpath.query.php

Note that when you run $xpath->query() on a malformed XPath, you will also get PHP Warnings; I put an @ in the last line so you won't see them.

Finally, one thing: The xpath you give as being invalid -- /foo/bar/@baz/@boy -- is not, in fact, invalid.

like image 179
romulusnr Avatar answered Jul 04 '26 16:07

romulusnr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!