Create CSV file separated by commas with PHP

3

I am generating a csv file from MySQL with PHP / PDO. I put the header, generate the list but record them continuously.

<?php
require ('includes/config.php');
$BD = new ConnDB();

$archivo_csv = "saldos.csv";
if(!file_exists($archivo_csv)){
    file_put_contents($archivo_csv,"Código,Nombre,Importe");
}

$sql = "SELECT cod, nom, saldo from cuentas where flag = 'X'";
$sth = $BD->query($sql);
$sth->execute();

if ($sth->rowCount() > 0) { 
    while ($fila = $sth->fetch(PDO::FETCH_ASSOC))
        {
        file_put_contents($archivo_csv,"n".join(",",$fila),FILE_APPEND);
        }
    }
?>

This is the exit:

  

Code, Name, Importen8, ALYDAR, 135.00n21, SANTA WATER, 1442.00n30

What is the error?

    
asked by Piropeator 24.10.2017 в 01:50
source

3 answers

3

You need to add line breaks \n . And to avoid platform problems, you can use our friend instead of \n PHP_EOL .

Although, I would use more optimized code to handle the file and to create the csv.

  • With fputs you can write to the file.

  • With the use of fopen we can create the file if it does not exist and at the same time verify if it is available or not, since it returns false if it does not exist or can not be created.

    <?php
    require ('includes/config.php');
    $BD = new ConnDB(); 
    
    $archivo_csv = fopen('saldos.csv', 'w');
    
    if($archivo_csv)
    {
        fputs($archivo_csv, "Código, Nombre, Importe".PHP_EOL));  
    
        $sql = "SELECT cod, nom, saldo from cuentas where flag = 'X'";
        $sth = $BD->query($sql);
        $sth->execute();
    
        if ($sth->rowCount() > 0) 
        { 
            while ($fila = $sth->fetch(PDO::FETCH_ASSOC))
            {
               fputs($archivo_csv, implode($fila, ',').PHP_EOL);
            }
        }
    
        fclose($archivo_csv);
    }else{
    
        echo "El archivo no existe o no se pudo crear";
    
    }
    
    ?>
    

Here a test of a result:

Código,Nombre,Importe
1,Juan Crisóstomo,1
2,Agustín,1
3,Teofilacto,0
4,Alcuino,0
5,Ireneo,1
6,Cirilo,1
7,Hilario,1
    
answered by 24.10.2017 / 02:41
source
3

Use fputcsv is a php function created to write in csv format and it already receives an array so that you will have no problem entering the parameters.

require ('includes/config.php');
$BD = new ConnDB();

$i = 0;
do {

  $archivo_csv = "saldos_$i.csv"
  $i++;
} while(file_exists($archivo_csv));

$csv = fopen($archivo_csv, 'x+');
fputcsv($csv,array ('Código','Nombre','Importe'));


$sql = "SELECT cod, nom, saldo from cuentas where flag = 'X'";
$sth = $BD->query($sql);


if ($sth->execute() !==  false  && $sth->rowCount() > 0) { 


  while ($fila = $sth->fetch(PDO::FETCH_ASSOC)) {
    fputcsv($csv, $fila);
  }


}

fclose($csv);
    
answered by 24.10.2017 в 06:10
-2

If what you need is a generated file that distributes each data in a separate cell, use the PHPExcel library. You just have to include it in your script, and consult some of the examples of generated files that it contains. I tell you, you'll end that in a blink.

Greetings!

    
answered by 24.10.2017 в 02:25