Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse html using PHP and loop through table rows and columns?

I'm trying to parse HTML from loadHTML but I'm having trouble, I managed to loop through all <tr>s in the document but I don't know how to loop through the <td> s on each row.

This is what I did so far:

$DOM->loadHTML($url);
$rows= $DOM->getElementsByTagName('tr');

for ($i = 0; $i < $rows->length; $i++) { // loop through rows
    // loop through columns
    ...
}

How can I get loop through the columns in each row?

like image 602
lisovaccaro Avatar asked Feb 17 '23 22:02

lisovaccaro


1 Answers

DOMElement also supports getElementsByTagName:

$DOM = new DOMDocument();
$DOM->loadHTMLFile("file path or url");
$rows = $DOM->getElementsByTagName("tr");
for ($i = 0; $i < $rows->length; $i++) {
    $cols = $rows->item($i)->getElementsbyTagName("td");
    for ($j = 0; $j < $cols->length; $j++) {
        echo $cols->item($j)->nodeValue, "\t";
        // you can also use DOMElement::textContent
        // echo $cols->item($j)->textContent, "\t";
    }
    echo "\n";
}
like image 64
Salman A Avatar answered Mar 03 '23 18:03

Salman A