使用 PHP 的 SimpleXML 检测空 XML 节点

问题描述 投票:0回答:4

首先我要说的是,我不熟悉解析 XML 和/或编写 PHP。我一直在研究和拼凑我正在做的事情,但我陷入了困境。

我正在尝试创建一个基本的 if/else 语句:如果节点不为空,则写入节点的内容。

这是我调用的 XML 片段:

<channel>
    <item>
      <title>This is a test</title>
      <link />
      <description>Test description</description>
      <category>Test category</category>
      <guid />
    </item>
  </channel>

这是我迄今为止拥有的 PHP:

<?php
    $alerts = simplexml_load_file('example.xml');
    $guid = $alerts->channel->item->guid;

    if ($guid->count() == 0) {
    print "// No alert";
}
    else {
        echo "<div class='emergency-alert'>".$guid."</div>";
}

?>

显然,“guid”是一个空节点,但它正在返回:

<div class="emergency-alert"> </div>

我做错了什么? :(

PS,我尝试过 hasChildren() 但也不起作用。

php simplexml nodes isnullorempty
4个回答
5
投票

@Wrikken 是对的。 XPath 是查询 XML 文档的首选方式。但回答你的问题,在你的简单情况下,你可以通过将 SimpleXMLElement 转换为字符串来检查节点值是否为空:

if ( !$guid->__toString() ) {
    print "No alert";
}

5
投票

在 PHP 中,表示空 XML 元素(自关闭标签或没有内容的空打开/关闭标签对)的 SimpleXMLElement 转换为布尔值

FALSE
。这可能有点出乎意料,因为通常 PHP 中的每个对象都会转换为布尔值
TRUE
:

var_dump((bool) new SimpleXMLElement("<guid/>")); # bool(false)

var_dump((bool) new SimpleXMLElement("<guid></guid>")); # bool(false)

var_dump((bool) new SimpleXMLElement("<guid> </guid>")); # bool(true)

此特殊规则记录在 PHP 手册的转换为布尔值中。

您可以利用它来检查您拥有的

<guid>
元素是否为 empty。然而,这里很重要的是,您专门要求该元素。在您现有的代码中:

$guid = $alerts->channel->item->guid;

您并不是要求特定的

<guid>
元素,而是要求所有属于父
<item>
元素的子元素。这些类型的 SimpleXMLElement 对象会转换为布尔值 true,除非它们包含零个元素(与您使用
SimpleXMLElement::count()
相比)。

与此不同,如果您通过索引获取第一个

<guid>
元素,您将获得该索引的 SimpleXMLElement
NULL
,以防该元素不存在(这意味着不存在
<guid>
元素)。

两者 - 不存在的元素如

NULL
或现有的空元素 - 将转换为布尔值
false
,可以在 if/else 语句中轻松使用:

$guid = $alerts->channel->item->guid[0];
                                    ### zero is the index of the first element
if ((bool) $guid) {
    # non-empty, existing <guid> element
} else {
    # empty or non-existing
}

这回答了你的问题。


3
投票
foreach($alerts->xpath("//item/guid[normalize-space(.)!='']") as $guid){
        echo "<div class='emergency-alert'>".$guid."</div>";
}

它有什么作用?

  1. xpath:查询xml文档的简单方法
  2. 标准化空间:删除了前导、尾随和重复空格的参数字符串(即:
    <guid> </guid>
    不是空字符串,而是
    ' '
    ,但是这个将其转换为
    ''
  3. .
    是节点的文本内容

0
投票

就像在您的示例中一样,我通过对象调用获取 xml 节点。我得到了我需要的数组,但对应节点有错误,如下所示:

        $responseStatus = (array)$xml->Body->AddPersonNewResponse->AddPersonNewResult->errors;

    $responseStatus = $responseStatus
        ? SkalaMethodResponseStatusesEnum::ERROR->value
        : SkalaMethodResponseStatusesEnum::SUCCESS->value;
© www.soinside.com 2019 - 2024. All rights reserved.