Skip to content
PHP Logo

How can the PHP code be modified to retrieve only the desired data from the HTML content?

To retrieve only the desired data from the HTML content, you can use PHP DOMDocument and DOMXPath to target specific elements or attributes based on their class, id, tag name, etc. By using XPath queries, you can narrow down the selection to only the elements you want to extract data from.

php
// Load the HTML content into a DOMDocument
$html = file_get_contents('example.html');
$dom = new DOMDocument();
$dom->loadHTML($html);

// Use DOMXPath to query specific elements based on class, id, tag name, etc.
$xpath = new DOMXPath($dom);
$desiredData = $xpath->query("//div[@class='desired-class']/p/text()");

// Loop through the results and output the desired data
foreach ($desiredData as $data) {
    echo $data->nodeValue . "<br>";
}