Pablo Viquez Blog

Mi vida y cosas relacionadas

Skip to: Content | Sidebar | Footer

How to use json_encode with ISO-8859-1 data – Part1

17 July, 2009 (13:51) | debug, iso 8859-1, PHP, utf-8, Web Development | By: Pablo Viquez

Download the demo files

While I was looking at some AJAX calls, I started to have a problem, for some reason, when I tried to query a JSON service I did using JQuery, the result was null for some fields.

Going a little deeper, I notice that the records from the DB were OK, and the JavaScript was OK to, so what was the problem? The JSON Encode!

So take for instance this code:

$customer =
    array(
        'id'    => 1,
        'name'  => 'Pablo Víquez',
        'notes' => 'Pruebas de encoding con JSON. á é í ó ú, ñ, Ñ'
);

echo json_encode();

If I save it as a ISO-8859-1, the result is the following:

{"id":1,"name":null,"notes":null}

Now, using the same code, but saving the PHP file as UTF-8 I got this result:

{"id":1,"name":"Pablo V\u00edquez","notes":"Pruebas de encoding con JSON. \u00e1 \u00e9 \u00ed \u00f3 \u00fa, \u00f1, \u00d1"}

The problem that I had was that the site was built using ISO 8859-1 not UTF-8, and changing it to UTF-8 is not an option, andn the AJAX call must return a JSON response.

json_encode documentation

string json_encode ( mixed $value [, int $options= 0 ] )

  • $value: The value being encoded. Can be any type except a resource.
    This function only works with UTF-8 encoded data.
  • $options (PHP 5.3 ONLY): Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT. Defaults to 0.