How to get nodes in first level using PHP DOMDocument?

dom, php

Solution

You may have to go outside of DOMDocument - maybe convert to SimpleXML or DOMXpath

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);
$elements = $xpath->query("/");

Problem

I'm new to PHP DOM object and have a problem I can't find a solution. I have a DOMDocument with following HTML: ``` <div id="header"> </div> <div id="content"> <div id="sidebar"> </div> <div id="info"> </div> </div> <div id="footer"> </div> ``` I need to get all nodes that are on first level (header, content, footer). hasChildNodes() does not work, because first level node may not have children (header, footer). For now my code looks like: ``` $dom = new DOMDocument(); $dom -> preserveWhiteSpace = false; $dom -> loadHTML($html); $childs = $dom -> getElementsByTagName('div'); ``` But this gets me all div's. any advice?

Original source