XPath find if an attributes value is in a array list

Viewed 805

I would like to select with xpatch all <a> tags that have the href attribute equal to a value present in an array with a list of urls.

Although I have found many examples on stackoverflow all of them return me this error: <b> Warning </b>: DOMXPath :: query (): Invalid expression in...

this is the code i tested without success:

$xpath->query("//a[@href=('facebook.com', 'google.com', 'amazon.com')]");

if try with one value work correctly, like this:

$xpath->query("//a[@href=('facebook.com')]");

but if i try to add a multi-value return the error mentioned, i have an array with around 1000 URL and i want select all link that have the href attributes value present in my array.

this is the code for load with xpatch the DOM loaded with DOMDocument

$dom = new DOMDocument( '1.0', 'utf-8' );
         
$xpath = new DomXpath($dom);

I would like to clarify that speed of execution is important to me. In your opinion, is it faster to select all the links and then make a check outsite xpatch through a foreach loop with in_array or is it faster to insert the condition directly into xpatch ?

1 Answers

Testing against a list of values requires XPath 2.0, but the PHP DOMXPath library only supports XPath 1.0. Therefore, you cannot use

//a[@href=('facebook.com', 'google.com', 'amazon.com')]

Instead, use

//a[@href='facebook.com' or @href='google.com' or @href='amazon.com']

As to execution speed relative to other alternatives, such as using XPath to acquire all a elements and iterating in the hosting language to filter those of interest, follow the universal rule of performance evaluation: Measure, don't guess (or ask others to guess for you).

Related