CSV Wrong Encoding

Tags: , ,



I have an array composed by just numbers and I use the following script to export in CSV

<?php
header('Content-Type: application/csv; charset=iso-8859-1');
session_start();
 
$tidyUp = array();
$index = 0;
foreach($_SESSION['report'] as $date => $values){
    $tidyUp[$index][] =$date;
    foreach($values as $title => $value)
        $tidyUp[$index][] = $value;
    $index += 1;
}
exportToCsv($tidyUp);
function exportToCsv($array, $filename = "export.csv", $delimiter=",") {
    $f = fopen('php://output', 'w');
    // loop over the input array
    foreach ($array as $line) {
        // generate csv lines from the inner arrays
        fputcsv($f, $line , $delimiter);
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}  
?>

The result is in the following image

Here a dump of the given array

array ( 0 => array ( 0 => '2019-10-29', 1 => 0, 2 => '45', 3 => 0, 4 => 0, 5 => 45, ), 1 => array ( 0 => '2019-10-30', 1 => 45, 2 => '165', 3 => '25', 4 => '26', 5 => 211, ), 2 => array ( 0 => '2019-10-31', 1 => 211, 2 => '12', 3 => '120', 4 => 0, 5 => 103, ), )

Any suggestion?

Answer

Check the encoding of $_SESSION[‘report’] data. It is possible that it uses some multi-byte characters. Use iconv on your $line before passing it to fputcsv function.



Source: stackoverflow