Convert HTML to CSV in php?

后端 未结 3 1533
春和景丽
春和景丽 2021-01-13 01:14

I have a html table structure like this;

            
                ID
                

        
3条回答
  •  不要未来只要你来
    2021-01-13 02:05

    You can load them in an array using the PHP DOM classes

    $data = array();
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $rows = $doc->getElementsByTagName('tr');
    foreach($rows as $row) {
        $values = array();
        foreach($row->childNodes as $cell) {
            $values[] = $cell->textContent;
        }
        $data[] = $values;
    }
    

    You can then convert that array to CSV data like in your example, or just simply build the CSV string directly in the loops.

    Live example

提交回复
热议问题