Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode function: special characters

Tags:

json

php

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'"); 
like image 715
user2723490 Avatar asked Dec 20 '13 00:12

user2723490


People also ask

What does the PHP function json_encode () do?

PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Parameters: $value: It is a mandatory parameter which defines the value to be encoded.

What is json_encode and json_decode in PHP?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

How do I encode a string in JSON?

In jQuery you can use the following code to encode the json: var data = {"key1":"value1", "key2":"value2","key3":"value3",...}; $. each(data,function(index,value)){ alert(index+" | "+value); });


1 Answers

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()
like image 181
scrowler Avatar answered Oct 06 '22 02:10

scrowler