weixin_33725270 2016-10-05 14:34 采纳率: 0%
浏览 37

将表格转换为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);
  • 写回答

1条回答 默认 最新

  • weixin_33697898 2016-10-05 15:18
    关注

    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");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog