【问题标题】:Check is a node exist and check it's attribute value检查是否存在节点并检查其属性值
【发布时间】:2019-04-11 07:37:00
【问题描述】:

我有一个带有节点和属性的 xml 文件

<hotspot name="hs1"/>
<hotspot name="hs2"/>
<hotspot name="hs3"/>

我想检查 nodc 热点是否存在以及是否存在特定的属性值。 我正在尝试这个,但 id 不起作用...

<?php
$file = 'hotspots.xml';
$xml = simplexml_load_file($file);
$var = $xml->xpath("//hotspot[@name='hs2']");
if (isset($var)) { echo 'does exist' } else {echo 'does not exist'}
?>

好吧,它根本不起作用(错误 500) 很抱歉成为这样的新手,非常感谢您的帮助!谢谢 !

【问题讨论】:

  • 这不是 XML 文件。另请参阅此问题的答案:stackoverflow.com/q/845021/1255289
  • 它是我的 xml 文件的一部分 ;)
  • @jeromebg 我的回答对你有用吗?

标签: php xpath attributes nodes simplexml


【解决方案1】:

您的 echo 语句应以 ; 结尾

$file = 'hotspots.xml';
$xml = simplexml_load_file($file);
$var = $xml->xpath("//hotspot[@name='hs2']");
if (isset($var)) {
    echo 'does exist';
} else {
    echo 'does not exist';
}

除此之外,$xml-&gt;xpath 的返回类型是一个数组,当 xpath 表达式没有找到结果时,它会返回一个空数组。

当它返回一个空数组时,isset($var) 将是 true,并且会给你 does exist,这是不正确的。

一种选择是使用count 来检查数组是否包含超过0 个项目:

if (count($var) &gt; 0) {

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2020-12-03
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多