How to count all nodes in DOMDocument

bart

New Member
#1
Using PHP 7.1 I want to count the number of nodes in the root of this string:
Mã:
<p>Lorem</p>
<p>Ipsum</p>
<div>Dolores</div>
<b>Amet</b>
Using following PHP:
Mã:
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($content);
$root = $dom->documentElement;
$children = $root->childNodes;
var_dump($children)
Returns:
Mã:
object(DOMNodeList)#4 (1) {
  ["length"]=>
  int(1)
}
I don't understand why the string of HTML only returns as 1 node. Additionally, I am unable to iterate through the nodes.
 

Admin

Administrator
Thành viên BQT
#2
For the record ( and despite other answer being accepted, here is the correct way to list the child nodes :). This includes the text nodes, which people forget are there!
Mã:
<?php

$content = "
  <p>Lorem</p>
  <p>Ipsum</p>
  <div>Dolores</div>
  <b>Amet</b>
 ";

$dom = new DOMDocument;
$dom->loadHTML($content);
$nodes=[];
$bodyNodes = $dom->getElementsByTagName('body');  // returns DOMNodeList object
foreach($bodyNodes[0]->childNodes as $child)      // assuming 1 <body> node
{
    $nodes[]=$child->nodeName;
}

print_r($nodes);
Outputs this, illustrating the point...:
Mã:
Array
(
    [0] => p
    [1] => #text
    [2] => p
    [3] => #text
    [4] => div
    [5] => #text
    [6] => b
    [7] => #text
)
 
OP
OP
B

bart

New Member
#3
Thanks! The trick thing is that HTML and BODY nodes are being added automatically by loadHTML(), which allows you to perform getElementsByTagName('body'). I was stuck there.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top