Converting HTML Table to a CSV automatically using PHP?

后端 未结 8 1747
一整个雨季
一整个雨季 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:45

    To expand on the accepted answer I did this which allows me to ignore columns by class name and also deals with blank rows/columns.

    You can use str_get_html http://simplehtmldom.sourceforge.net/. Just include it and away you go! :)

    $html = str_get_html($html); // give this your HTML string
    
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename=sample.csv');
    
    $fp = fopen("php://output", "w");
    
    foreach($html->find('tr') as $element) {
      $td = array();
      foreach( $element->find('th') as $row) {
        if (strpos(trim($row->class), 'actions') === false && strpos(trim($row->class), 'checker') === false) {
          $td [] = $row->plaintext;
        }
      }
      if (!empty($td)) {
        fputcsv($fp, $td);
      }
    
      $td = array();
      foreach( $element->find('td') as $row) {
        if (strpos(trim($row->class), 'actions') === false && strpos(trim($row->class), 'checker') === false) {
          $td [] = $row->plaintext;
        }
      }
      if (!empty($td)) {
        fputcsv($fp, $td);
      }
    }
    
    fclose($fp);
    exit;
    

提交回复
热议问题