Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting HTML Table to a CSV automatically using PHP?

Tags:

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 = '<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>'; 

Guys, I just need $table to convert in only .csv file, which could be automatically generated using some PHP function. We can define path for that csv file to /test/home/path_to_csv

like image 923
Thompson Avatar asked May 08 '12 12:05

Thompson


People also ask

How Export HTML table data from Excel to PHP?

php $file="demo. xls"; $test="<table ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>"; header("Content-type: application/vnd. ms-excel"); header("Content-Disposition: attachment; filename=$file"); echo $test; ?>


1 Answers

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); 
like image 170
Baba Avatar answered Sep 19 '22 13:09

Baba