Search code examples
phphtmldomdomdocument

Q: How to find a section from a web page without using XPath


I need to extract a section from a web page. I need a version with DOM API and without XPath. This is my version. Need to extract from "Latest Distributions" and display the information in browser.

<?php
$result = file_get_contents ('https://distrowatch.com/');

libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->loadHTML($result);
$xpath = new DOMXPath($doc);

$node = $xpath->query('//table[@class="News"]')->item(0);

echo $node->textContent;

Solution

  • This seems pretty straightforward, but it's a waste of time to do this instead of XPath.

    <?php
    $result = file_get_contents ('https://distrowatch.com/');
    
    libxml_use_internal_errors(true);
    
    $doc = new DOMDocument();
    $doc->loadHTML($result);
    foreach ($doc->getElementsByTagName("table") as $table) {
        if ($table->getAttribute("class") === "News") {
            echo $table->textContent;
            break;
        }
    }