Munib
Munib

Reputation: 3661

How to loop through all the Childs under a tag in PHP DOMDocument

I have the following html

$html =  '<body><div style="font-color:#000">Hello</div>
<span style="what">My name is rasid</span><div>new to you 
</div><div style="rashid">New here</div></body>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$elements = $dom->getElementsByTagName('body');

I have tried

foreach($elements as $child)
 {
        echo $child->nodeName;
 }

The Ouput is

body

But I need to loop through all the tags under body not the body. How can I do that.

I have also tried in above example to replace

$elements = $dom->getElementsByTagName('body');

with

$elements = $dom->getElementsByTagName('body')->item(0);

But It gives Error. Any Solution??

Upvotes: 3

Views: 6437

Answers (3)

Decent Dabbler
Decent Dabbler

Reputation: 22783

If you only want child nodes of the body element, you can use:

$body = $dom->getElementsByTagName( 'body' )->item( 0 );
foreach( $body->childNodes as $node )
{
    echo $node->nodeName . PHP_EOL;
}

If you want all descending nodes of the body element, you could use DOMXPath:

$xpath = new DOMXPath( $dom );
$bodyDescendants = $xpath->query( '//body//node()' );
foreach( $bodyDescendants as $node )
{
    echo $node->nodeName . PHP_EOL;
}

Upvotes: 3

Praveen kalal
Praveen kalal

Reputation: 2129

use this code

 $elements = $dom->getElementsByTagName('*');


        foreach($elements as $child)
        {

              echo $child->nodeName;

        }

Upvotes: 0

adydy
adydy

Reputation: 50

try this

    $elements = $dom->getElementsByTagName('*');
    $i = 1; //counter to output from 3rd one, since foreach loop below will output" html  body div span div div"

    foreach($elements as $child)
    {

    if ($i > 2) echo $child->nodeName."<br>";   //output "div span div div"
    ++$i;
    }

Upvotes: 1

Related Questions