Otros consejos

Por un comentario en el sitio PHP

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>

A medida que el autor de la pregunta original, quería "escritura en el navegador sobre la marcha", tal vez vale la pena señalar (como era mi caso y nadie lo mencionó) que si desea forzar un nombre de archivo y un cuadro de diálogo que pide descargar un archivo en el navegador, debe configurar los encabezados apropiados antes de dar salida a cualquier cosa con fputcsv:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=myFile.csv');

La producción de un CSV en realidad no es tan difícil (análisis de un CSV es un poco más complicado).

Código de ejemplo para escribir una matriz 2D como CSV:

$array = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
];

// If this CSV is a HTTP response you will need to set the right content type
header("Content-Type: text/csv"); 

// If you need to force download or set a filename (you can also do this with 
// the download attribute in HTML5 instead)
header('Content-Disposition: attachment; filename="example.csv"')

// Column heading row, if required.
echo "Column heading 1,Column heading 2,Column heading 3\n"; 

foreach ($array as $row) {
    $row = array_map(function($cell) {
        // Cells containing a quote, a comma or a new line will need to be 
        // contained in double quotes.
        if (preg_match('/["\n,]/', $cell)) {
            // double quotes within cells need to be escaped.
            return '"' . preg_replace('/"/', '""', $cell) . '"';
        }

        return $cell;
    }, $row);

    echo implode(',', $row) . "\n";
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top