简体   繁体   中英

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

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("\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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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