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

前端 未结 3 773
南笙
南笙 2021-01-19 15:31

I\'m trying to parse HTML from loadHTML but I\'m having trouble, I managed to loop through all s in the document but I don\'t know how to loop through

3条回答
  •  迷失自我
    2021-01-19 16:18

    Use DOMXPath to query out the child column nodes with a relative xpath query, like this:

    $xpath = new DOMXPath( $DOM);
    $rows= $xpath->query('//table/tr');
    
    foreach( $rows as $row) {
        $cols = $xpath->query( 'td', $row); // Get the  elements that are children of this 
        foreach( $cols as $col) {
            echo $col->textContent;
        }
    }
    

    Edit: To start at specific rows and stop, keep your own index on the row by changing how you're iterating over the DOMNodeList:

    $xpath = new DOMXPath( $DOM);
    $rows= $xpath->query('//table/tr');
    
    for( $i = 3, $max = $rows->length - 2; $i < $max, $i++) {
        $row = $rows->item( $i);
        $cols = $xpath->query( 'td', $row);
        foreach( $cols as $col) {
            echo $col->textContent;
        }
    }
    

提交回复
热议问题