How to iterate to get all results of xpath->evaluate

Asked

Viewed 50 times

0

In general to iterate elements xpath I use a loop as follows:

<?php
$dom = new DOMDocument;
$dom->loadHTML('<div class="xGh">Test1</div><div class="xGh">Test2</div><div class="xGh">Test3</div>');

$xpath = new DOMXpath($dom);
$xpatyQ = "//div[@class=\"xGh\"]";
$img = $xpath->query($xpatyQ);
for($i = 0; $i < $img->length; $i++)
{   echo $xpath->query("//div[@class=\"xGh\"]")->item($i)->nodeValue."<br/>";
}//Test1<br/>Test2<br/>Test3<br/>
?>

Now my doubt is how to iterate when the result comes through the evaluate(), ex:

<?php
$dom = new DOMDocument;
$dom->loadHTML('<div class="xGh" style="background-image: url(\'name_file.jpg\');"></div><div class="xGh" style="background-image: url(\'name_file1.jpg\');"></div><div class="xGh" style="background-image: url(\'name_file2.jpg\');"></div>');

$xpath = new DOMXpath($dom);
$xpatyQ = "substring-before(substring-after(//*[@class=\"xGh\"]/@style, \"background-image: url('\"), \"')\")";
$img = $xpath->query($xpatyQ);
$result = $xpath->evaluate($xpatyQ);
echo $result;//name_file.jpg

How to iterate to get the other results?

The desired exit:

name_file.jpgname_file1.jpgname_file2.jpg

1 answer

1


You will get the result this way:

<?php
$dom = new DOMDocument;
$dom->loadHTML('<div class="xGh" style="background-image: url(\'name_file.jpg\');"></div><div class="xGh" style="background-image: url(\'name_file1.jpg\');"></div><div class="xGh" style="background-image: url(\'name_file2.jpg\');"></div>');

$xpath = new DOMXpath($dom);

$imgs = $xpath->query('//*[@class="xGh"]');

foreach($imgs as $b){
    $data[] = array(
        'img' => $xpath->evaluate(
            "substring-before(substring-after(./@style, \"background-image: url('\"), \"')\")",
        $b
        ),
    );
}

die(var_dump($data));

http://sandbox.onlinephpfunctions.com/code/254e14de06bead8e3c90a9346f0683721e4fc192

  • Perfect, I’ll try to understand... but I don’t know xpath shorted here,,vlw, man

Browser other questions tagged

You are not signed in. Login or sign up in order to post.