PHP:documentElement-> childNodes警告 [英] PHP: documentElement->childNodes warning

查看:49
本文介绍了PHP:documentElement-> childNodes警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$xml = file_get_contents(example.com);

$dom = new DomDocument();
$dom->loadXML($xml);

$items = $dom->documentElement;

foreach($items->childNodes as $item) { 
 $childs = $item->childNodes;
 foreach($childs as $i) {
  echo $i->nodeValue . "<br />";
 }
}

现在我在每2nd foreach中都会收到此警告:

Now I get this warning in every 2nd foreach:

Warning: Invalid argument supplied for foreach() in file_example.php  on line 14

请帮助大家。谢谢!

推荐答案

某些节点没有子节点,因此您将一个null(无效)参数传递给foreach(就像警告说的那样。)

Some nodes don't have children, so you're passing a null (invalid) argument to the foreach (just like the warning says).

要避免出现警告,您需要检查当前节点是否有任何子节点。为此,您可以使用 DOMNode :: hasChildNodes() 方法:

To avoid the warnings you need to check if the current node has any children. For that you can use the DOMNode::hasChildNodes() method:

foreach($items->childNodes as $item) { 
    if ($item->hasChildNodes()) {
        $childs = $item->childNodes;
        foreach($childs as $i) {
            echo $i->nodeValue . "<br />";
        }
    }
}

这篇关于PHP:documentElement-&gt; childNodes警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆