I am generating a csv file from MySQL with PHP/PDO. I put the header, I generate the list but it records 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 output:
Code,Name,Importen8,ALYDAR,135.00n21,AGUA SANTA,1442.00n30
What is the mistake?
You need to add the line breaks
\n
. And to avoid platform issues, you can use\n
our friend insteadPHP_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 check if it is available or not, since it returnsfalse
if it does not exist or cannot be created.Here's a proof of a result:
Use fputcsv, it is a php function created to write in csv format, it also receives an array so you will not have a problem entering the parameters.
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'm telling you, you'll be done with that in a heartbeat.
Cheers!