Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json with special characters like é

I'm developing a dependent select script using jQuery, PHP and JSON as the response.

Everything goes well except for using special characters like French ones (é , è , à...)

if I pre-encode them like (é , è , à) (Here I'm using spaces between the ampersand and the rest of the word to prevent auto encoding in my question) it works but when rendered with jquery the characters are not converted to what they should look like (é...), instead they are shown as is (é)

If I write them like (é) and don't pre-encode them the full value in this array entry is not shown.

What should I do here?

Thanks.

like image 546
medk Avatar asked Sep 02 '11 13:09

medk


2 Answers

If I write them like (é) and don't pre-encode them the full value in this array entry is not shown.

What should I do here?

In JSON you do not HTML-encode values. You send them literally (é) and set set Content-Type correctly:

header('Content-Type: application/json; Charset=UTF-8');

Declare the encoding your data is in, of course.

like image 95
Tomalak Avatar answered Oct 23 '22 20:10

Tomalak


This worked for me, hopefully it will work for anyone else experiencing similar issues.

$title = 'é';
$title = mb_convert_encoding($title, "UTF-8", "HTML-ENTITIES");

header('Content-Type: application/json; Charset="UTF-8"');
echo json_encode(array('title' => $title));

The mb_convert_encoding function takes a value and converts it from (in this case) HTML-ENTITIES to UTF-8.

See here for me details on the function http://php.net/manual/en/function.mb-convert-encoding.php

like image 33
rharvey Avatar answered Oct 23 '22 22:10

rharvey