json_encode function: special characters

Elements of an array containing special characters are converted to empty strings when encoding the array with json_encode:

$arr = array ( "funds" => "ComStage STOXX®Europe 600 Techn NR ETF", "time"=>....);
$json = json_encode($arr);

After JSON encoding the element [funds] is null. It happens only with special characters (copyright, trademark etc) like the ones in "ComStage STOXX®Europe 600 Techn NR ETF".

Any suggestions?

Thanks

UPDATE: This is what solved the problem prior to populating the array (all names are taken from the db):

$mysqli->query("SET NAMES 'utf8'");

Solution 1:

The manual for json_encode specifies this:

All string data must be UTF-8 encoded.

Thus, try array_mapping utf8_encode() to your array before you encode it:

$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);

// {"funds":"ComStage STOXX\u00c2\u00aeEurope 600 Techn NR ETF"}

For reference, take a look at the differences between the three examples on this fiddle. The first doesn't use character encoding, the second uses htmlentities and the third uses utf8_encode - they all return different results.

For consistency, you should use utf8_encode().

Docs

  • json_encode()
  • utf8_encode()
  • array_map()

Solution 2:

Your input has to be encoded as UTF-8 or ISO-8859-1.

http://www.php.net/manual/en/function.json-encode.php

Because if you try to convert an array of non-utf8 characters you'll be getting 0 as return value.


Since 5.5.0 The return value on failure was changed from null string to FALSE.