简体   繁体   English

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

[英]PHP How to convert large txt file to csv and force download

I have large txt file(1GB), and allow user to download with 2 formats, TXT and CSV 我有一个很大的txt文件(1GB),并允许用户以2种格式(TXT和CSV)下载

I create download.php file. 我创建download.php文件。

$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("\n", $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. 该代码适用于小型txt文件。

But it not work for large file. 但是它不适用于大文件。

Thanks 谢谢

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. PHP具有一个名为readfile的函数,该函数将文件的内容回显到输出缓冲区, 而不同时将整个文件加载到内存中 -您应该将其用于TXT变量而不是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. 对于CSV版本,应该使用fopen打开文件,然后使用fgets逐行读取文件,并将转换后的内容回显到输出缓冲区。 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. 请接受我对您措辞不佳而可能收到的反对票的哀悼。

https://superuser.com/questions/581702/how-can-i-convert-a-txt-file-to-csv-format-without-using-excel https://superuser.com/questions/581702/how-can-i-convert-a-txt-file-to-csv-format-without-using-excel

apparently you can just rename it by changing the file extension if it is formatted correctly 显然,如果格式正确,您可以通过更改文件扩展名来重命名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM