PHP: json_encode and json_decode with UTF-8

I have the following array:

Array
(
    [1] => Array
        (
            [time] => 07:30
            [event] => Celebrity Organ Recital â€" Sophie-Véronique Cauchefer-Choplin
        )
)

(original event line: "Celebrity Organ Recital - Sophie-Véronique Cauchefer-Choplin", I used htmlentities with ENT_QUOTES)

When I use json_encode, the event string is returned as NULL and it is saved as an empty string in MySQL.

If I do not use htmlentities. I will get this in my database: "Celebrity Organ Recital u2013 Sophie-Vu00e9ronique Cauchefer-Choplin". I have used many methods, but I still cannot convert this string to the original one.

I really need some hints, I hope you could give me a solution to encode a UTF-8 string, as above, in json, and then save it in MySQL and then decode back to its original. I searched for a while, but still can't find a solution.

Thank you very much!

+3
source share
1 answer

It seems to me that you do not need to sanitize values ​​in sql queries http://php.net/manual/en/function.mysql-real-escape-string.php

A simple example: We have a table with the structure:

CREATE TABLE `test` (
    `text` VARCHAR(1024) NULL DEFAULT '0'
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB

And php script

   header("Content-type:text/html;charset=utf8");
    $ar = array
        (
            1 => Array
                (
                    'time' => '07:30',
                    'event' => 'Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin'
                )
        );

    $mysqli = new mysqli('localhost','root', '', 'test');

    $mysqli -> query("INSERT INTO `test` (`text`) VALUES ('" . json_encode($ar) . "')"); // we not escape characters like \, ", '

// now we use mysqli::real_escape_string
    $mysqli -> query("INSERT INTO `test` (`text`) VALUES ('" . $mysqli -> real_escape_string(json_encode($ar)) . "')"); // here we escape characters

    $mysqli_result = $mysqli -> query("SELECT * FROM `test");
    while($result = $mysqli_result -> fetch_assoc()){
        var_dump(json_decode($result["text"],true));
    }

The result var_dumpis:

array
  1 => 
    array
      'time' => string '07:30' (length=5)
      'event' => string 'Celebrity Organ Recital u2013 Sophie-Vu00e9ronique Cauchefer-Choplin' (length=68)

array
  1 => 
    array
      'time' => string '07:30' (length=5)
      'event' => string 'Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin' (length=63)

Second var_dumpis normal

+3
source

All Articles