doucha4054 2013-09-05 12:17
浏览 62
已采纳

通过SimpleXML返回XPath函数的结果

It seems that PHP SimpleXML XPath doesn't allow to get results of XPath functions:

$s = new \SimpleXMLElement('<test><node>A</node><node>B</node></test>');
var_dump($s->xpath("count(node)"));

Returns an empty array:

array(0) {
}

While Using DOM returns the expected value 2:

$dom = new \DOMDocument();
$dom->loadXML('<test><node>A</node><node>B</node></test>');
$xpath = new \DOMXPath($dom);
var_dump($xpath->evaluate("count(node)"));


float(2.0)

Is there a way to do the same directly with SimpleXML?

  • 写回答

1条回答 默认 最新

  • dousao6260 2013-09-05 18:25
    关注

    PHP's SimpleXML only works on queries which return nodesets. count(...) returns a scalar value which is not supported. Use DOMXPath which is much more capable or count the objects in the result array:

    var_dump(count($s->xpath("node")));
    

    int(2)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?