How can SimpleXML or DOM be used to parse HTML tables in PHP?
To parse HTML tables in PHP using SimpleXML or DOM, you can first load the HTML content into a SimpleXML object or a DOMDocument object. Then, you can navigate through the HTML structure to locate the table elements and extract the data within them. This can be done by looping through the rows and cells of the table and extracting the content as needed.
$html = file_get_contents('example.html');
// Using SimpleXML
$xml = new SimpleXMLElement($html);
$table = $xml->xpath('//table')[0];
foreach ($table->tr as $row) {
foreach ($row->td as $cell) {
echo $cell . "<br>";
}
}
// Using DOM
$dom = new DOMDocument();
$dom->loadHTML($html);
$table = $dom->getElementsByTagName('table')[0];
foreach ($table->getElementsByTagName('tr') as $row) {
foreach ($row->getElementsByTagName('td') as $cell) {
echo $cell->nodeValue . "<br>";
}
}
Keywords
Related Questions
- What are some potential pitfalls to avoid when using PHP to manipulate table row colors based on user actions?
- In what ways can the URL be utilized to control the display of specific months in a PHP calendar application?
- What are the benefits of implementing a Retry-Policy when dealing with file_get_contents() errors in PHP?