Steven Hammons Steven Hammons - 2 months ago 6
HTML Question

How to find element in already parsed HTML data

Here I have a very simple code to grab all the 'div' elements with the classname 'info_block'. I am wondering how would I go about finding another element with the classname 'price' from within 'info_block' and display it instead of the whole 'info_block' element.
Main Goal: Find the price in each element with classname 'info_block'. but do inside the foreach, because I may need to find other elements.

<?php
$page = file_get_contents('example.com');
$dom = new DOMDocument();
$dom->loadHTML($page);
$xpath = new DOMXPath($dom);
$div1 = $xpath->query('//div[@class="info_block"]');
foreach ($div1 as $var1){
//echo $dom->saveHTML($var1);
}
?>


There is a element in each of the 'info_block' with a classname 'price' and I would like to display only that element. Like so...

foreach ($div1 as $var1){
$dom2 = new DOMDocument();
$dom2->loadHTML($dom->saveHTML($var1));
$xpath2 = new DOMXPath($dom2);
$div2 = $xpath2->query('//div[@class="price"]');
$div2 = $div2->item(0);
echo $dom2->saveHTML($div2);
}


But instead of just giving me the price it returns the whole HTML for 'info_block' as it did before.

Answer

You could provide each <div class="info_block"> found and search for <div class="price">" by providing it in the second argument of ->query():

$div1 = $xpath->query('//div[@class="info_block"]'); 
foreach ($div1 as $var1){ 
    $div2 = $xpath->query('./div[@class="price"]', $var1); 
                                             //     ^ each div
    $div2 = $div2->item(0);
    echo $dom->saveHTML($div2);
}

Note: You do not need to create another instance of DOM and DOMXpath.

This example is taken into context of this kind of HTML semantic:

<div class="info_block"> // each info block
    <div class="price">1</div> // inside of it has price
</div>
<div class="info_block">
    <div class="price">2</div>
</div>