Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nodes in first level using PHP DOMDocument?

Tags:

dom

php

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?

like image 846
Deniss Kozlovs Avatar asked Dec 30 '25 19:12

Deniss Kozlovs


1 Answers

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("/");
like image 109
ChronoFish Avatar answered Jan 02 '26 11:01

ChronoFish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!