Converting HTML Table to a CSV automatically using PHP?

后端 未结 8 1743
一整个雨季
一整个雨季 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条回答
  • 2020-12-02 20:07

    Assuming that out_str has your html table data

    $csv = $out_str;
            $csv = str_replace("<table class='gradienttable'>","",$csv);
            $csv = str_replace("</table>","",$csv);
            $csv = str_replace("</td><td>",",",$csv);
            $csv = str_replace("<td>","",$csv);
            $csv = str_replace("</td>","",$csv);
            $csv = str_replace("</font>","",$csv);
            $csv = str_replace("</tr>","",$csv);
            $csv = str_replace("<tr>","\n",$csv);
    

    Remove any CSS from the file

            $csv = str_replace("<font color='yellow'>","",$csv);
            $csv = str_replace("<font color='red'>","",$csv);
            $csv = str_replace("<font color='green'>","",$csv);
            $csv = str_replace("</th><th>",",",$csv);
            $csv = str_replace("<th>","",$csv);
            $csv = str_replace("</th>","",$csv);
    
            file_put_contents('currentFile.csv',$csv);
    

    Output the file currentFile.csv to the user

    Hope it helps!

    0 讨论(0)
  • 2020-12-02 20:08

    You can use str_get_html http://simplehtmldom.sourceforge.net/

    include "simple_html_dom.php";
    $table = '<table border="1">
    <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    </tr>
    <tr>
    <td>row 1, cell 1</td>
    <td>row 1, cell 2</td>
    </tr>
    <tr>
    <td>row 2, cell 1</td>
    <td>row 2, cell 2</td>
    </tr>
    </table>';
    
    $html = str_get_html($table);
    
    
    
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename=sample.csv');
    
    $fp = fopen("php://output", "w");
    
    foreach($html->find('tr') as $element)
    {
            $th = array();
            foreach( $element->find('th') as $row)  
            {
                $th [] = $row->plaintext;
            }
    
            $td = array();
            foreach( $element->find('td') as $row)  
            {
                $td [] = $row->plaintext;
            }
            !empty($th) ? fputcsv($fp, $th) : fputcsv($fp, $td);
    }
    
    
    fclose($fp);
    
    0 讨论(0)
提交回复
热议问题