Search code examples
phpexport-to-csv

PHP can't write big data to csv file


I'm using the PHP code to export data to CSV file from table (Database).

But unfortunately its writing just 98000 rows and i have total 198000 rows in table.

I think total data upto 34mb in the table.

And second thing how can i download automatically once the file writing finished. Anyone can help thanks.

$que = "SELECT * FROM campaign";
$query = mysqli_query($connection,$que);
$number_rows = mysqli_num_rows($query);

if ($number_rows >= 1)
{
    $filename = "exported_db_" . date("m-d-Y_hia") . ".csv"; // filenme with date appended
    $fp = fopen($filename, "w"); // open file

    $row = mysqli_fetch_assoc($query);

    $seperator = "";
    $comma = "";

    foreach ($row as $name => $value)
    {
        $seperator .= $comma . $name; // write first value without a comma
        $comma = ","; // add comma in front of each following value
    }
    $seperator .= "\n";

    echo "Database has been exported to $filename";

    fputs($fp, $seperator);

    mysqli_data_seek($query, 0); // use previous query leaving out first row

    while($row = mysqli_fetch_assoc($query))
    {
        $seperator = "";
        $comma = "";

        foreach ($row as $name => $value)
        {
            $seperator .= $comma . $value; // write first value without a comma
            $comma = ","; // add comma in front of each following value 
        }

        $seperator .= "\n";

        fputs($fp, $seperator);
    } 

    fclose($fp);

}
else {
    echo "There are no records in the database to export.";
}

Solution

  • When i put these two line code at the top of file, So i have get correct result.
    I think these code increase the size of caches_memory and execution time.
    Thanks everyone for commenting and discussion.

    
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', '180');