query will return a DOMNodeList regardless of your actual XPath expression. This suggests that you do not know what the result may be. Thus, you can iterate over the list and check the node type of nodes and do something based on this type.
But query not limited to this use case. You can still use this when you know what type you will get. In the future, what you wanted to achieve may be more understandable, and therefore easier to maintain.
evaluate , on the other hand, gives you exactly the type you choose. As the examples show:
$xpath->evaluate("1 = 0"); // FALSE $xpath->evaluate("string(1 = 0)"); // "false"
As it turned out, the choice of attributes //div/@id or text nodes //div/text() still gives a DOMNodeList instead of strings. Therefore, potential use cases are limited. You would have to enclose them in string : string(//div/@id) or text nodes string(//div/text()) .
The main benefit of evaluate is that you can get lines from a DOMDocument with fewer lines of code. Otherwise, it will return the same result as query .
ThW's answer is correct that some expressions will not work with query :
$xpath->query("string(//div/@id)") // DOMNodeList of length 0 $xpath->evaluate("string(//div/@id)") // string with the found id
source share