"converting html table to a csv automatically using php?" Answer’s


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

include "simple_html_dom.php";
$table = '<table border="1">
<th>Header 1</th>
<th>Header 2</th>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>

$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);

Wednesday, March 31, 2021
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :