JSON does not accept accent

3

Friends, I have a problem, the string that has an accent can not get it using JSON:

$imagens = array();
$sql = mysql_query("SELECT * FROM texto_index");
while ($row = mysql_fetch_row($sql)){
      $imagens[] = $row;
}
echo json_encode($imagens);

For example: comes as null

the array:

Array ( [0] => Array ( [0] => 5 [1] => RECEITUÁRIOS [2] => MASCULINOS [3] => 1 [4] => #ffffff [5] => 56 [6] => 28 [7] => Direita [8] => cache/1404135032s-receituario-feminino-eco2.jpg ) [1] => Array ( [0] => 6 [1] => ÓCULOS [2] => MASCULINOS [3] => 1 [4] => #ffffff [5] => 52 [6] => 20 [7] => esquerda [8] => cache/1404225957262.jpg ) )
    
asked by anonymous 01.07.2014 / 18:13

2 answers

4

Put in your first line your code like this:

header("Content-Type: text/html; charset=UTF-8",true)

and after the connection put this line

mysql_set_charset('utf8');
$imagens = array();
$sql = mysql_query("SELECT * FROM texto_index");
while ($row = mysql_fetch_row($sql)){
  $imagens[] = $row;
}
echo json_encode($imagens);

Preferably always use UTF-8 by default

They can also be done this way:

mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');

Example on doubt Json notation Ideone

    
01.07.2014 / 18:26
0

When using string in ISO-8859-1 charset (latin1), the json_encode function of php presents problems, cutting the value after the first accented character.

To avoid this problem, before converting to json, simply convert the string to UTF-8.

In php, to do this conversion, just use the utf8_encode function.

Likewise, this type of problem should occur with other types of character encodings other than UTF-8. It is therefore recommended that you always use UTF-8, especially when you need to work with the native PHP functions that work with JSON, both json_encode and json_decode.

Try to do a test as follows and see if it solves your problem:

<?php 

    $imagens = array();
    $sql = mysql_query("SELECT * FROM texto_index");
    while ($row = mysql_fetch_row($sql)){
        $imagens['id']   = $row[0];
        $imagens['n1']   = utf8_encode($rom[1]);
        $imagens['n2']   = utf8_encode($rom[2]);
        $imagens['n3']   = $row[3];
        $imagens['cor']  = $row[4];
        $imagens['w']    = $row[5];
        $imagens['h']    = $row[6];
        $imagens['lado'] = $row[7];
        $imagens['link'] = $row[8];
    }
    echo json_encode($imagens);

?>
    
01.07.2014 / 18:29