php – 如何使用XPath检查节点是否存在
发布时间:2020-05-26 16:01:48 所属栏目:PHP 来源:互联网
导读:我正在使用 PHP和XPath连接到基于远程XML的API.来自服务器的示例响应如下所示. OTA_PingRS Success / EchoDataThis is some test data/EchoData /OTA_PingRS 您可以看到没有起始标记 Success那么如何搜索 Success /的存在?使用Xpath?
|
我正在使用 PHP和XPath连接到基于远程XML的API.来自服务器的示例响应如下所示. <OTA_PingRS>
<Success />
<EchoData>This is some test data</EchoData>
</OTA_PingRS>
您可以看到没有起始标记< Success>那么如何搜索< Success />的存在?使用Xpath? 谢谢 你可以test for existence of nodes with the XPath function
要使用DOMXPath执行此操作,您需要使用 $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 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
