Seth
Seth

Reputation: 123

Converting Table to CSV

I'm using str_get_html http://simplehtmldom.sourceforge.net/ to export an HTML table to CSV. The user completes a form and the same table displays on screen. If they check a form box, I would like it to also generate a CSV file for download (in addition to displaying the table on screen).

Using ajax, I have the table being displayed in an empty div element.

<script type="text/javascript">
    $(document).ready(function() {  
    var options = {target: '#output1'}; 
    $('#completed').ajaxForm(options);});  
</script>

It's almost working. The only problem is that it displays the CSV content in the div update, rather than generating a file for download. If I remove the on-screen display of the table and remove the ajax functionality, it generates the CSV file perfectly. Can someone help me with the code below so that it will generate a file for download?

    include 'simple_html_dom.php';

    $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)
    {
        $td = array();
        foreach( $element->find('th') as $row)  
        {
            $td [] = $row->plaintext;
        }
        fputcsv($fp, $td);

        $td = array();
        foreach( $element->find('td') as $row)  
        {
            $td [] = $row->plaintext;
        }
        fputcsv($fp, $td);
    }

    fclose($fp);

Upvotes: 1

Views: 611

Answers (1)

Lucha Laura Hardie
Lucha Laura Hardie

Reputation: 449

Instead of using "php://output", you need to use a path/filename. Right now, you are telling php to write to the output buffer mechanism.

For example:

$fp = fopen("path/to/filename.csv", "w");

Upvotes: 1

Related Questions