phpjsoncsvexport-to-csvcyrillic

Json to csv with cyrillic


This is my php code:

<?php 
$jsonData = file_get_contents("1.json");
$jsonDecoded = json_decode($jsonData);

$csv = '1.csv';
$fileCsv = fopen($csv, 'w');
foreach($jsonDecoded as $i){
    fputcsv($fileCsv, $i);
}

fclose($fileCsv);

?>

In 1.json I have data written in cyrillic. Whene 1.csv is opened via Excel, there is a problem with decoding it. It shows me non-cyrillic random symbols. Why is it so? How can I fix it?

I'm not sure where this problem comes from. It could be just problem with Excel? I'm using Excel 2016.

The desired ecxel: enter image description here

How it actually looks like: enter image description here


Solution

  • A utf8 CSV file has a Byte Order Mark as its first three octets. These are the hex values 0xEF, 0xBB, 0xBF. So you can do:

    $fileCsv = fopen($csv, 'w');
    fprintf($fileCsv, chr(0xEF).chr(0xBB).chr(0xBF));
    foreach($jsonDecoded as $i){
        fputcsv($fileCsv, $i);
    }
    
    fclose($fileCsv);