Search code examples
phputf-8special-charactersjson

PHP: Issues reading and writing data(with special characters) to file


I am having issues reading-writing data(with special-characters) to file.

I am doing something like this:

//Writing data..
<?php
   header('Content-Type: text/html; charset=utf-8');

   $file = 'filename.db';
   $data = 'Some string with special characters';

   //Writing to the file..
   @file_put_contents($file, json_encode($data));

?>

This works fine. When I open the db file in Notepad ++, the data is proper. Special characters are also stored properly:

 //Reading data..
 <?php
   header('Content-Type: text/html; charset=utf-8');

   $file = 'filename.db';

   //Reading from the file..
   $data = file_get_contents($file);
   $data = json_decode(utf8_encode(stripslashes($data)));

   echo $data;

 ?>

This displays the special characters as "????" or sometimes like "u00cf" or some other characters.

What is going wrong, and where?

Any help would be appreciated, Thanks.


Solution

    1. If you're not storing arrays or other complex data structures you do not need JSON.
    2. When reading from the file, why in god's name do you mistreat the data by stripping slashes and running it through utf8_encode? That's what's destroying the JSON format and thereby your data.

    Just write the raw string into a file and read it back as is, done!

    $string = 'ユーティーエッフエイト';
    file_put_contents('file.txt', $string);
    $string = file_get_contents('file.txt');
    

    Nothing more you need to do.