How can a PHP DOM Parser be used to extract and manipulate table values in PHP?
To extract and manipulate table values using a PHP DOM Parser, you can load the HTML content containing the table into a DOMDocument object, then use DOMXPath to query for the table elements and iterate through the rows and cells to extract and manipulate the data.
<?php
// Load the HTML content into a DOMDocument
$html = file_get_contents('example.html');
$dom = new DOMDocument();
$dom->loadHTML($html);
// Use DOMXPath to query for the table element
$xpath = new DOMXPath($dom);
$table = $xpath->query('//table')->item(0);
// Iterate through the rows and cells of the table
foreach ($table->getElementsByTagName('tr') as $row) {
foreach ($row->getElementsByTagName('td') as $cell) {
// Extract and manipulate the cell value
$value = $cell->nodeValue;
// Manipulate the value as needed
echo $value . " ";
}
echo "<br>";
}
?>