How can the dynamic extraction of data from HTML tables be achieved using DOMDocument in PHP?

To dynamically extract data from HTML tables using DOMDocument in PHP, you can load the HTML content into a DOMDocument object, then use DOMXPath to query and extract the desired data from the table elements.

<?php
$html = '<table>
            <tr>
                <td>John</td>
                <td>Doe</td>
            </tr>
            <tr>
                <td>Jane</td>
                <td>Smith</td>
            </tr>
        </table>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$tableRows = $xpath->query('//table/tr');

foreach ($tableRows as $row) {
    $rowData = [];
    foreach ($row->childNodes as $cell) {
        $rowData[] = $cell->nodeValue;
    }
    echo implode(', ', $rowData) . PHP_EOL;
}
?>