dpg2905 2014-01-03 17:04
浏览 150
已采纳

PHP如何将大型txt文件转换为csv并强制下载

I have large txt file(1GB), and allow user to download with 2 formats, TXT and CSV

I create download.php file.

$file = $_GET['file'];
$type= $_GET['type'];
$pathfile = "/some/path/".$file.".txt";
$isifile = file_get_contents($pathfile);
    if($type == "TXT"){
        header('Content-disposition: attachment; filename="'.$file.'.txt"');
        header('Content-type: text/plain');
        echo $isifile;
    }else if($type == "CSV"){
        $arr_file = explode("
", $isifile); //will die here because array need large memory
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=".$file.".csv");
        foreach($arr_file as $wd ){
            echo $wd;
        }
    }

The code is work for small txt file.

But it not work for large file.

Thanks

  • 写回答

2条回答 默认 最新

  • donglu1973 2014-01-03 17:10
    关注

    PHP has a function named readfile that echoes the contents of a file to the output buffer without loading the entire file into memory at the same time -- you should use that for the TXT variant instead of file_get_contents/echo.

    For the CSV version, you should use fopen to open the file and then fgets to read it, line by line, and echo the converted content to the output buffer. The code for that might look something like this...

    $fileObj = fopen( $pathfile, "rt" );
    while ( ( $line = fgets( $fileObj ) ) ) // by default this will read one line at a time
    {
        //  If you need to do anything to transform this data to CSV format, convert each line here.
        echo $line;
    }
    

    Please accept my condolences for the downvotes you are likely to receive for poorly wording your question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?