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

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要