1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

When you open the resulting file in hex editor how does the data look like? Is there any byte order mark? Are the characters stored as single or multi-byte values?
To be honest can't say it to you, but I can post you there result: link
There is no BOM at the beginning of the file. Every character is a single byte and new line character is 0A in hexadecimal. However, it seems that you do not have equal number of columns in those first two lines that are in the screenshot. If you open the file in a simple text editor it should display just fine. I am assuming Libre Office on Mac has a problem with either the new line character or with the column count.
Opening with text editor works, but how can I make it also working as CSV? P.S. Is Ubuntu not a Mac
update: on usual office from Microsoft it work smoothly, thank you for help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.