PHP: documentElement-> childNodes warning

$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 second foreach:

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

Please help the guys. Thank!

+3
source share
1 answer

Some nodes do not have children, so you pass a null (invalid) argument to foreach (as indicated in the warning).

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

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

Source: https://habr.com/ru/post/1738416/


All Articles