What is the difference between DOMXPath::evaluate and DOMXPath::query?

后端 未结 2 1355
余生分开走
余生分开走 2020-12-19 07:52

Trying to decide which is more appropriate for my use case...

After comparing the documentation for these methods, my vague understanding is evaluate returns a typed

2条回答
  •  孤城傲影
    2020-12-19 08:16

    query will return a DOMNodeList regardless of your actual XPath expression. This suggests that you don't know what the result may be. So you can iterate over the list and check the node type of the nodes and do something based on the type.

    But query is not limited to this use case. You can still use this when you know what type you will get. It may be more readable in the future what you wanted to achieve and therefore easier to maintain.

    evaluate on the other hand gives you exactly the type that you select. As the examples point out:

    $xpath->evaluate("1 = 0"); // FALSE
    $xpath->evaluate("string(1 = 0)"); // "false"
    

    As it turns out selecting attributes //div/@id or text nodes //div/text() still yields DOMNodeList instead of strings. So the potential use cases are limited. You would have to enclose them in string: string(//div/@id) or text nodes string(//div/text()).

    The main advantage of evaluate is that you can get strings out of your DOMDocument with fewer lines of code. Otherwise it will produce the same output as query.

    ThW's answer is right 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
    

提交回复
热议问题