generate csv file with php

0

Good afternoon, I have a problem generating a csv file and opening it with excel, this opens showing all the data but does not separate them by column only places in column A here I share the code

public function generar_excel(){
    $condiciones = $_SESSION['condiciones']['condiciones'];   
    $data_excel = $this->modelo_base_m->seguimiento_excel($condiciones); 
    //prp($data_excel,1);

    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"Seguimientos_Menores_5\""); 

    $outputBuffer = fopen("php://output", 'w');


    foreach ($data_excel as $i => $valor) {
        fputcsv($outputBuffer, $valor,';');
    }

    fclose($outputBuffer);
    exit;
    $this->index();
}

in the fputcsv line I put the third semicolon parameter so that it separates them but in the same way places them in a cell.

    
asked by Angel Gutierrez 22.01.2018 в 18:27
source

1 answer

0

Assuming that $valor is an array, I suggest you try these options:

  • Change the Content-Type to text/csv .
  • Remove line Content-Transfer-Encoding: Binary since CSVs are text files (not binary).

If the above does not work, you could try explicitly indicating to the CSV which separator you are using. For this you must add to the beginning of the CSV file a line that contains only this text:

sep=;

You can try opening the CSV file with Notepad ++ and adding this line at the beginning, and then open with Excel to see if it works. If so, you must add that line to your php script, for example:

$outputBuffer = fopen("php://output", 'w');
fwrite($outputBuffer, 'sep=;' . "\r\n"; // <-- agregar esta línea
foreach ($data_excel as $i => $valor) { // ...

Sources:

answered by 22.01.2018 в 19:56