php simplexml 检查是否有孩子点头?
我有很多 xml
文件,我不想获取值,但检查它们是否有孩子点头。所以我使用 count
而不是 foreach
。但如果第一个 $xml->book
中没有 $xml->book->date
,我的代码总是回显 no
鲁普。
$xml = simplexml_load_file('some.xml');
if (@count($xml->book->date)>0){
echo 'yes';
}else{
echo 'no';
}
像这样的 xml 树
<?xml version="1.0" encoding="utf-8"?>
<Catalog>
<book>
<title/><description/><price/>
</book>
<book>
<title/><description/><price/>
<date/> //(optional, there may be 0 to n [book] elements having a [date] element in the document)
</book>
<book>
<title/><description/><price/>
</book>
<book>
<title/><description/><price/>
<date/>
</book>
</Catalog>
对于本文档,“count($xml->book->date)”工作版本的结果应该是 2,即 > 0
编辑:也许不使用count
,但如何检查整个xml文件中是否有date
子节点?谢谢。
I have many xml
file's, I do not want to get the value, but check if they have a child child nod or no. so I use count
instead of foreach
. but my code always echo no
if there have no $xml->book->date
in the first $xml->book
roop.
$xml = simplexml_load_file('some.xml');
if (@count($xml->book->date)>0){
echo 'yes';
}else{
echo 'no';
}
the xml tree like this
<?xml version="1.0" encoding="utf-8"?>
<Catalog>
<book>
<title/><description/><price/>
</book>
<book>
<title/><description/><price/>
<date/> //(optional, there may be 0 to n [book] elements having a [date] element in the document)
</book>
<book>
<title/><description/><price/>
</book>
<book>
<title/><description/><price/>
<date/>
</book>
</Catalog>
For this document the result of the working version of "count($xml->book->date)" should be 2, i.e. > 0
EDIT: maybe do not use count
, but how to check if have or not have date
childnod in the whole xml file? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不尝试使用 xpath 呢?
http://www.php.net/manual/en/simplexmlelement.xpath.php
http://www.w3schools.com/xpath/xpath_syntax.asp
Why don't you try with xpath?
http://www.php.net/manual/en/simplexmlelement.xpath.php
http://www.w3schools.com/xpath/xpath_syntax.asp
如果你想签入整个 xml 文档,那么我认为你必须循环遍历所有的 book 元素 -
If you want to check in the entire xml document, then I think you'll have to loop through all the book elements-
我想你不需要在 count(....) 之前添加“@”。尝试没有那个
I guess you don't need that '@' before count(....). Try without that