PHP: documentElement->childNodes warning

19,639

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 />";
        }
    }
}
Share:
19,639
Loreto Gabawa Jr.
Author by

Loreto Gabawa Jr.

SOreadytohelp

Updated on June 05, 2022

Comments

  • Loreto Gabawa Jr.
    Loreto Gabawa Jr. about 2 years
    $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!

    • Gordon
      Gordon over 14 years
      The error message suggests that $childs is not an iterable type. Please provide a short extract of the XML you are parsing.
    • Loreto Gabawa Jr.
      Loreto Gabawa Jr. over 14 years
      @Gordon, thanks! i am bad at naming vars ;)