0

I want to pass the result of a mysql query out as JSON in PHP 5.6.3. The data contains non alphanumeric characters, particularly in this case the 'degrees' symbol (as in '45º').

json_encode seems to fail silently if the data contains such characters:

$json = json_encode($my_obj);

I can make the encode step work by using utf8_encode on the offending properties:

$my_obj->description = utf8_encode($my_obj->description);

...but then I get output like this: '45º' which is not desirable.

The database table uses UTF-8 Unicode encoding (utf_unicode_ci) and the data appears to be stored and retrieved successfully. It just breaks json_encode when it finds these characters.

How to solve this?

Ade
  • 2,961
  • 4
  • 30
  • 47
  • 1
    There is no such thing as "special characters". There are only characters and an encogind. – arkascha Mar 27 '15 at 19:17
  • 1
    Sounds a little like your application server (php here) does _not_ use unicode. In that case you want to fix that. – arkascha Mar 27 '15 at 19:18
  • Json encoding fails for non utf8 strings. Are you shure you stored your data as proper utf8 characters? Did you set names utf8 in your db conn? And did you set meta charset utf8 in your html? – steven Mar 27 '15 at 19:38
  • If I render the output to HTML there is no problem with the character set. The content renders correctly. And the PHP framework (CodeIgniter) is running the query "SET NAMES utf8" automatically. I will check the data is stored correctly. – Ade Mar 27 '15 at 20:20
  • Please do check all the items mentioned in the duplicate. You may also want to go through this: [Handling Unicode Front To Back In A Web App](http://kunststube.net/frontback/). One of these will very likely solve your problem. If it does not, add details about all the individual points discussed and how you are handling them in your case. – deceze Mar 27 '15 at 20:37

0 Answers0