我正在尝试使用 xpath 检查某个元素是否出现多次。
XML:
<XML>
<containers>
<container id="1">
</container>
<container id="2">
</container>
</containers>
</XML>
我尝试使用以下简单的 xpath 表达式
$xml->xpath('/XML/containers/container');
我得到了:
Element='<container id="1">
</container>'
Element='<container id="2">
</container>'
但结果我想要一个类似数组的东西
$containers = array('container', 'container');
如何存档?
最佳答案
您不需要数组来检查匹配数。只需 count()
XPath 的结果,即可得到您的数字:
$a = '<XML>
<containers>
<container id="1">
</container>
<container id="2">
</container>
</containers>
</XML>';
$xml = simplexml_load_string($a);
$containers = $xml->xpath('/XML/containers/container');
$totalContainers = count($containers); // 2
关于php - xpath - 检查元素是否出现多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46426640/