php – 如何使用XPath检查节点是否存在

前端之家收集整理的这篇文章主要介绍了php – 如何使用XPath检查节点是否存在前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 PHP和XPath连接到基于远程XML的API.来自服务器的示例响应如下所示.
<OTA_PingRS>
        <Success />
        <EchoData>This is some test data</EchoData>
    </OTA_PingRS>

您可以看到没有起始标记< Success>那么如何搜索< Success />的存在?使用Xpath?

谢谢
西蒙

<成功/> element是 empty element,意思是没有价值.它是开始和结束标记.

你可以test for existence of nodes with the XPath function boolean()

The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN
  • a node-set is true if and only if it is non-empty
  • a string is true if and only if its length is non-zero
  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type

要使用DOMXPath执行此操作,您需要使用DOMXPath::evaluate()方法,因为它将返回一个类型化结果,在本例中为布尔值:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
$successNodeExists = $xpath->evaluate('boolean(/OTA_PingRS/Success)');

var_dump($successNodeExists); // true

demo

当然,您也可以只查询/ OTA_PingRS / Success并查看返回的DOMNodeList中是否有结果:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
$successNodeList = $xpath->evaluate('/OTA_PingRS/Success');

var_dump($successNodeList->length);

demo

你也可以使用SimpleXML

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$nodeCount = count(simplexml_load_string($xml)->xpath('/OTA_PingRS/Success'));

var_dump($nodeCount); // 1
原文链接:https://www.f2er.com/php/240289.html

猜你在找的PHP相关文章