How can the DOM be utilized to achieve the desired outcome of extracting data from an HTML table in PHP?
To extract data from an HTML table in PHP, you can utilize the DOM (Document Object Model) to parse the HTML content and extract the table data. By using DOM functions like `getElementsByTagName()` and `nodeValue`, you can target specific table elements and retrieve their content. This allows you to access and manipulate the table data within your PHP script.
<?php
$html = file_get_contents('example.html'); // Get the HTML content of the page
$dom = new DOMDocument();
$dom->loadHTML($html); // Load the HTML content into the DOM
$table = $dom->getElementsByTagName('table')->item(0); // Get the first table element
$rows = $table->getElementsByTagName('tr'); // Get all rows in the table
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td'); // Get all cells in the row
foreach ($cells as $cell) {
echo $cell->nodeValue . " "; // Output the cell content
}
echo "<br>";
}
?>