February 1, 2013

SOLVED: json_encode() setting some fields to null even if they contain values…

Filed under: Tips — Tags: — Webopius @ 8:31 pm

OK, this is a really quick tip.

PHP’s json_encode() function takes an object as an argument and returns a JSON format string. Really useful for lots of things, especially when writing web services.

However, there’s a nasty issue that will only catch you out with some types of data. Sometimes, json_encode() sets a field’s value to NULL even if that field contains perfectly valid text. The reason for this is that json_encode ONLY works with UTF-8 encoded data, so if the object you’re passing to it contain non-UTF8 characters, that value gets set to NULL.

If you are using MySQL to retrieve data being passed to json_encode(), the solution is to add this line before any SELECT statements:

mysql_query('SET CHARACTER SET utf8');

After that, all is fine.

  • Tags