Converting HTML Table to a CSV automatically using PHP?

后端 未结 8 1771
一整个雨季
一整个雨季 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 19:48

    You can do this with arrays and regular expressions... See below

    $csv = array();
    preg_match('/| [^>]*>)(.*?)<\/table( |>)/is',$table,$b);
    $table = $b[2];
    preg_match_all('/| [^>]*>)(.*?)<\/tr( |>)/is',$table,$b);
    $rows = $b[2];
    foreach ($rows as $row) {
        //cycle through each row
        if(preg_match('/| [^>]*>)(.*?)<\/th( |>)/is',$row)) {
            //match for table headers
            preg_match_all('/| [^>]*>)(.*?)<\/th( |>)/is',$row,$b);
            $csv[] = strip_tags(implode(',',$b[2]));
        } elseif(preg_match('/| [^>]*>)(.*?)<\/td( |>)/is',$row)) {
            //match for table cells
            preg_match_all('/| [^>]*>)(.*?)<\/td( |>)/is',$row,$b);
            $csv[] = strip_tags(implode(',',$b[2]));
        }
    }
    $csv = implode("\n", $csv);
    var_dump($csv);
    

    Then you can use file_put_contents() to write the csv string to file..

提交回复
热议问题