PHP: documentElement->childNodes warning

你。 提交于 2019-12-23 19:28:33

问题


$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 />";
 }
}

Now I get this warning in every 2nd foreach:

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

Please help guys. Thanks!


回答1:


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

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 />";
        }
    }
}


来源:https://stackoverflow.com/questions/2511779/php-documentelement-childnodes-warning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!