I have the following code PHP
to create a file CSV
with information from the database MySQL
and save it in the directory where the file containing the code is exportar.php
.
<?php
require_once 'config.php';
$salida = fopen('saldos.csv', 'w');
if ($salida) {
# Los encabezados no son requeridos en este caso
# fputs($salida, "Documento, Obtenido, Acumulado, Nuevo".PHP_EOL);
$sql = "SELECT documento, obtenido, acumulado, nuevo FROM datos WHERE semana = 3 ";
$stmt = $dbcon->query($sql);
$stmt->execute();
if ($stmt->rowCount() > 0 ) {
while ($fila = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputs($salida, implode($fila, ';').PHP_EOL);
}
}
fclose($salida);
} else {
echo "Lo sentimos! No se pudo crear el archivo";
}
?>
What should I add so that it doesn't save the file but automatically downloads it instead?
To automatically download the file
.csv
, it will be necessary to modify the headers as follows.Content-Type To indicate the type of file or resource.
Content-Disposition ,
attachment
(indicating that it will be downloaded; followed by the filenamefilename
)readfile() for file output
csv.