Converting HTML Table to a CSV automatically using PHP?

后端 未结 8 1758
一整个雨季
一整个雨季 2020-12-02 19:20

I am just in need to convert a this html table automatically in csv using PHP. Can someone provide any idea how to do this? Thanks.

$table = \'
8条回答
  •  Happy的楠姐
    2020-12-02 20:07

    If anyone is using Baba's answer but scratching their head over extra white spaces being added, this will work:

    include "simple_html_dom.php";
    $table = '
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
'; $html = str_get_html($table); $fileName="export.csv"; header('Content-type: application/ms-excel'); header("Content-Disposition: attachment; filename=$fileName"); $fp = fopen("php://output", "w"); $csvString=""; $html = str_get_html(trim($table)); foreach($html->find('tr') as $element) { $td = array(); foreach( $element->find('th') as $row) { $row->plaintext="\"$row->plaintext\""; $td [] = $row->plaintext; } $td=array_filter($td); $csvString.=implode(",", $td); $td = array(); foreach( $element->find('td') as $row) { $row->plaintext="\"$row->plaintext\""; $td [] = $row->plaintext; } $td=array_filter($td); $csvString.=implode(",", $td)."\n"; } echo $csvString; fclose($fp); exit;

}

提交回复
热议问题