Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a CSV created by PHP directly in ISO encoding

Tags:

php

csv

iso

I am trying to create a CSV file using PHP. I want the ISO-8859-1 encoding. So far I managed to create the CSV file but it has an UTF-8 encoding.

I was able to make it work with utf8_decode thanks to this question which shows how to convert it from ISO to CSV, but my goal is to:

Create the file directly in ISO-8859-1 encoding directly.

Here is my code (without decode, ask me if you want it as well):

    $columns = array(
        'option1' => 'Option1 title',
        'option2' => 'Option2 title',
        'option3' => 'Option3 title'
    );

    /* Setting default values for the array */

    $default = array(
        'option1' => 'value1',
        'option2' => 'value2',
        'option3' => 'value3'
    );

    /* Creating the CSV file */

    $fp = fopen('/tmp/' . $this->fileName, "w");

    if ($fp) {
        fputcsv($fp, array_values($columns), ";");

        foreach ($legListArray as $row) {
            $data = array();

            foreach ($columns as $key => $_dummy) {

                if (substr($key, 0, 7) == "_field_") {
                    $data[] = $row[$key];
                } else {
                    $data[] = $default[$key];
                }
            }

            fputcsv($fp, $data, ";");
        }

        fclose($fp);
    }
like image 403
Relisora Avatar asked Feb 15 '26 00:02

Relisora


1 Answers

Just map the array using utf8_decode when calling fputcsv.

You only have two lines which are affected:

fputcsv($fp, array_map('utf8_decode', array_values($columns)), ";");
...
    fputcsv($fp, array_map('utf8_decode', $data), ";");

Or you can do utf8_decode when building the array, i.e.:

$data[] = utf8_decode($row[$key]);
...
$data[] = utf8_decode($default[$key]);
like image 142
Alex Shesterov Avatar answered Feb 16 '26 13:02

Alex Shesterov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!