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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With