How get first level of dom elements by Domdocument PHP?
Example with code that not works – tooken from Q&A:How to get nodes in first level using PHP DOMDocument?
<?php
$str=<<< EOD
<div id="header">
</div>
<div id="content">
<div id="sidebar">
</div>
<div id="info">
</div>
</div>
<div id="footer">
</div>
EOD;
$doc = new DOMDocument();
$doc->loadHTML($str);
$xpath = new DOMXpath($doc);
$entries = $xpath->query("/");
foreach ($entries as $entry) {
var_dump($entry->firstChild->nodeValue);
}
?>
The first level of elements below the root node can be accessed with
The childNodes property contains a
DOMNodeList, which you can iterate withforeach.See
DOMDocument::documentElementand
DOMNode::childNodesSince
childNodesis a property ofDOMNodeany class extendingDOMNode(which is most of the classes in DOM) have this property, so to get the first level of elements below aDOMElementis to access that DOMElement’s childNode property.Note that if you use
DOMDocument::loadHTML()on invalid HTML or partial documents, the HTML parser module will add an HTML skeleton with html and body tags, so in the DOM tree, the HTML in your example will bewhich you have to take into account when traversing or using XPath. Consequently, using
will only iterate the
<body>DOMElement node. Knowing that libxml will add the skeleton, you will have to iterate over the childNodes of the<body>element to get the div elements from your example code, e.g.However, doing so will also take into account any whitespace nodes, so you either have to make sure to set
preserveWhiteSpaceto false or query for the right element nodeType if you only want to getDOMElementnodes, e.g.or use XPath
Additional information: