Search code examples
phpcsvphp4

exporting a mysql query in php version 4 to a csv


Edit on my original post. I found the answer!!!! with help:)

I now have this working by using the below code with thanks for the advice on this in the comments:

<?php

$f = fopen('incident_csv\test.csv', 'w');

$query = "
select column1, column2, column3
from table
where columns = values
";

$var1 = mysql_query($query, $database connection variable);

/* From Monkey Zeus */

$csv_lines = array();

// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){

$columns = array();

// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}

// Join on a comma
$csv_lines[] = implode(',', $columns);
}

// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);

/* From Monkey Zeus */  

fwrite($f, $csv_file_string);

?>

Solution

  • You can do this:

    $csv_lines = array();
    
    // Loop your records from the DB
    while ($row = mysql_fetch_assoc($var1)){
    
        $columns = array();
    
        // Loop each column for the row
        foreach($row as $k=>$v){
            // Surround column item in double-quotes and escape double-quotes with double-double-quotes
            $columns[] = '"'.str_replace('"', '""', $v).'"';
        }
    
        // Join on a comma
        $csv_lines[] = implode(',', $columns);
    
        // Write to the file right away. You are using PHP4 so I imagine system memory is not plentiful
        // If you use this then there is no need for the "$csv_lines[] =" from above
        // nor the $csv_file_string after the while loop
        // fwrite($f, implode(',', $columns)."\n");
    }
    
    // fclose($f); // If you choose to write to the file during the while loop then close the file handle when you are finished
    
    // Create full CSV file by joining on a newline
    $csv_file_string = implode("\n", $csv_lines);