edwardffs
edwardffs

Reputation: 432

PHP UTF8 encoding issue with Special characters

I am using PHP to connect to a database and retrieve mostly strings. These strings are sentences written in Portuguese, therefore they have plenty of "é", "ç", "ú", etc...

When retrieving I'm doing this:

$res = sqlsrv_query($conn,$query);
$array_req = array();

while($rs = sqlsrv_fetch_object($res)){
    // Get info request
    $temp_req = array();
    $temp_req['id'] = $rs->id;
    $temp_req['title'] = utf8_decode($rs->title);
    ...
}
echo json_encode(array('result'=>$array_req));

And by doing that utf8_decode characters like "ç" get replaced by "?" for example. If I don't do the decoding then the text is all well since it is correctly stored on the database. However, if I don't do the decoding, the json_encode will retrieve the strings as null.

How do I keep the characters? I already tried mb_convert_encoding, htmlspecialchars, nothing seems to work.

EDIT: This script was being requested by an Android app. However I was testing on the browser and it seems if I actually encode the strings in UTF8 and send the json with the flag JSON_UNESCAPED_UNICODE sugested below, the browser still returns bad characters but the android app reads them ok. Go figure... This is the working code:

$res = sqlsrv_query($conn,$query);
$array_req = array();

while($rs = sqlsrv_fetch_object($res)){
    // Get info request
    $temp_req = array();
    $temp_req['id'] = $rs->id;
    $temp_req['title'] = utf8_encode($rs->title);
    ...
}
echo json_encode(array('result'=>$array_req), JSON_UNESCAPED_UNICODE);

Upvotes: 1

Views: 2000

Answers (1)

Scott C Wilson
Scott C Wilson

Reputation: 20036

utf8_decode is what is changing the characters into "?". You shouldn't do that - just use the data as is without processing it. Use the option JSON_UNESCAPED_UNICODE on json_encode and it should work.

json_encode(array('result'=>$str), JSON_UNESCAPED_UNICODE);

Upvotes: 1

Related Questions