0

I have a PHP (5.3) script that fetches data from a DB and pass it to android via JSON. The UTF-8 characters work only for Ä,Ü etc.

But not the russian and chinese letters!

Table

$createTableMessage = $db->prepare("CREATE TABLE IF NOT EXISTS message (
`id` int(11) unsigned NOT NULL auto_increment,
`fromusername` varchar(255) NOT NULL default '',
`tousername` varchar(255) NOT NULL default '',
`imageid` int(11) default null,
`text` varchar(255) default null,
`ispublic` int(11) default 0,
PRIMARY KEY  (`id`))
CHARACTER SET utf8 COLLATE utf8_general_ci");

function 'Send message'

...
$answerarray[] = array( 
"id" => $row['id'],
"countdown" => $row['-1'],
"answerText" => $row['text'],
"answerusername" => $row['fromusername'],
"filename" => $row[' '],
"country" => $row['country']
);

utf8_encode_deep($answerarray);
echo json_encode(array('answer'=>$answerarray));

function utf8_encode_deep (from the internet)

function utf8_encode_deep(&$input) {
if (is_string($input)) {
    $input = utf8_encode($input);
} else if (is_array($input)) {
    foreach ($input as &$value) {
        utf8_encode_deep($value);
    }

    unset($value);
} else if (is_object($input)) {
    $vars = array_keys(get_object_vars($input));

    foreach ($vars as $var) {
        utf8_encode_deep($input->$var);
    }
}
}
5
  • Get rid of utf8_encode_deep. PHP nowadays supports utf itself. Commented Feb 13, 2015 at 16:17
  • Then it does not even recognize Ä, Ö etc and returns null Commented Feb 13, 2015 at 16:21
  • At which point of the transmission does the payload become corrupted? Commented Feb 13, 2015 at 16:33
  • @Ulrich Eckhardt When I query it with PhpMyAdmin it works perfect. Once my android application receives it, it corrupts. Commented Feb 13, 2015 at 16:59
  • I got rid of utf8_encode_deep. That was correct. Furthermore I forgot to set the connection to UTF-8 Commented Feb 13, 2015 at 17:09

1 Answer 1

2

To successfully deliver utf8 characters you need to ensure that

  1. the database table and field,
  2. the connection to the database,
  3. the encoding of the php file itself
  4. content-type header of the file you output

is all utf8. If you get correct characters when you query the results manually in mysql the problem most probably lies on 3 or 4.

json encoding won't break the encoding if its correct in the first place. You can check if the data you get from mysql is correct (with print_r in PHP) before turning it into json string.

Sign up to request clarification or add additional context in comments.

1 Comment

I forgot the connection!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.