PHP return the nth row of a html table with dom

前端 未结 2 541
夕颜
夕颜 2021-01-23 03:35

I\'m trying to use the simplehtmldom (http://simplehtmldom.sourceforge.net/) to print out the nth row of a table. Currently nothing happens, is there anything else I need to do?

相关标签:
2条回答
  • 2021-01-23 04:00

    0 is the first row, so 8 would be the ninth:

    $ret = $html->find('tr', 8);
    
    0 讨论(0)
  • 2021-01-23 04:03

    Assuming row 9 is the row for TUE, you can also do this with PHP's inbuilt DOMDocument, which would save some memory and parsing time and not rely on a 3rd party script.

    <?php
    $html = file_get_contents('http://www.masjid-umar.org/downloads/timetable_apr.htm');
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    
    //TUE 1 1 4.37 6.39 1.08 5.35 9.18 6.00 1.30 6.30 7.42 9.40                 
    echo '
    <table>
        <tr>';
    foreach($dom->getElementsByTagName('table') as $table) {
        echo innerHTML($table->getElementsByTagName('tr')->item(9));
    }
    echo '
        </tr>
    </table>';
    
    function innerHTML($current){
        $ret = "";
        $nodes = @$current->childNodes;
        if(!empty($nodes)){
            foreach($nodes as $v){
                $tmp = new DOMDocument();
                $tmp->appendChild($tmp->importNode($v, true));
                $ret .= $tmp->saveHTML();
            }
            return $ret;
        }
        return;
    }
    ?>
    

    Your also want to look into caching the result for a day as the site is slooow ;p

    0 讨论(0)
提交回复
热议问题