首先让我说我不精通解析 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 中 SimpleXMLElement 它表示一个空的 XML 元素(自闭标签或没有内容的空打开/关闭标签对)转换为 bool 值 FALSE
.这可能有点出乎意料,因为通常 PHP 中的每个对象都会转换为 bool 值 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 手册 Converting to boolean 中。 .
您可以利用它来检查
<guid>
是否存在你拥有的元素是空的。但是这里很重要,您要特别要求元素。在您现有的代码中:$guid = $alerts->channel->item->guid;
您不是要特定的
<guid>
元素,但对于所有父元素的子元素 <item>
元素。这类 SimpleXMLElement 对象强制转换为 boolean true ,除非它们包含零元素(与您使用 SimpleXMLElement::count()
相比)。与此不同的是,如果您获得第一个
<guid>
按索引元素,你会得到一个 SimpleXMLElement 该指数或 NULL
如果元素不存在(也就是说,没有 <guid>
元素)。两者 - 不存在的元素为
NULL
或现有的空的 - 将转换为 bool 值 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
}
这将回答您的问题。
关于php - 使用 PHP 的 SimpleXML 检测空的 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659319/