0

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);
}
1

1 Answer 1

2

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,
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.