saurav
saurav

Reputation: 487

php dom get multiple element from loop

below is my html structure, i want output like : content inside post_message div and respective images

something like :

test 123 -> 1.png
test 1232 -> 2.png
test 1232 -> 3.png

Html content

<div class="abc">
    <div>
        <div class="udata">
            <div class="post_message"><p>test 123</p></div>
            <div class="">
                <img class="scaledImageFitWidth img" src="1.png">
            </div>
        </div>
    </div>
</div>
<div class="abc">
    <div>
        <div class="udata">
            <div class="post_message"><p>test 1232</p></div>
            <div class="">
                <img class="scaledImageFitWidth img" src="2.png">
                <img class="scaledImageFitWidth img" src="3.png">
            </div>
        </div>
    </div>
</div>

Below is my php code but it seems not working :

<?php 
$dom = new DomDocument();
// $dom->load($filePath);
@$dom->loadHTML($fop);
$finder = new DomXPath($dom);
$classname="udata";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

// print_r($nodes);

foreach ($nodes as $i => $node) {


    $entries = $finder->query("//*[contains(@class, 'post_message')]", $node);
    print_r($entries);

    $isrc  =  $node->query("//img/@src");
    print_r($isrc);
}

Upvotes: 0

Views: 32

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

When using XPath, you always need to make your XPath relative to the start node, so using the descendant axes to ensure you limit the subsequent search is only in the nodes part of the start point.

So the code would look more like...

foreach ($nodes as $i => $node) {
    $entries = $finder->query("descendant::*[contains(@class, 'post_message')]", $node);
    echo $entries[0]->textContent .":";

    $isrc  =  $finder->query("descendant::img/@src", $node);
    foreach ( $isrc as $src )   {
        echo $src->textContent.",";
    }
    echo PHP_EOL;
}

which would output

test 123:1.png,
test 1232:2.png,3.png,

Upvotes: 2

Related Questions