【问题标题】:Converting Table to CSV将表格转换为 CSV
【发布时间】:2016-10-05 14:34:09
【问题描述】:

我正在使用 str_get_html http://simplehtmldom.sourceforge.net/ 将 HTML 表格导出为 CSV。用户填写表格,屏幕上显示相同的表格。如果他们检查表单框,我希望它还生成一个 CSV 文件以供下载(除了在屏幕上显示表格)。

使用 ajax,我将表格显示在一个空的 div 元素中。

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

它几乎可以工作了。唯一的问题是它在 div 更新中显示 CSV 内容,而不是生成文件供下载。如果我删除表格的屏幕显示并删除 ajax 功能,它会完美地生成 CSV 文件。有人可以帮我编写下面的代码,以便生成文件供下载吗?

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

【问题讨论】:

    标签: php ajax csv export-to-csv


    【解决方案1】:

    您需要使用路径/文件名,而不是使用“php://output”。现在,您正在告诉 php 写入输出缓冲区机制。

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2010-11-27
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      相关资源
      最近更新 更多