Search code examples
phpfputcsv

Can't get a csv file using fputcsv() and an array returned by pg_fetch_xxx()


I am trying to export a csv file with php, using an array returned by pg_fetch_array. But the csv file is empty.

If I write an array by hand, the csv is correct. I tried to build an array from pg_fetch_all without success.

<?php
$listope = pg_fetch_array($marequete) ;

$fichier = fopen("export.csv", "w") ;

foreach ($listope as $line) {
    fputcsv($fichier, explode(',',$line));
}

fclose($fichier) ;
?>

I know that the problem is the $listope var which does not return a proper array but I can't find the solution. Thanks for help


Solution

  • Dont explode the array, the fputcsv() function does all that for you

    So simply do

    fputcsv($fichier, $line);
    

    Another thing, you only read one row from the result set, now that maybe because you only expect one row, but as you also code a loop, if the query would generate more than one row try this, using pg_fetch_all()

    $listope = pg_fetch_all($marequete) ;
    
    $fichier = fopen("export.csv", "w") ;
    
    foreach ($listope as $line) {
        fputcsv($fichier, $line);
    }
    
    fclose($fichier) ;
    

    Reference The manual