Accentuation in the JSON

Asked

Viewed 26,037 times

7

I have accentuation problems when printing JSON. If I use characters like ã, õ, ô, ç, some codes appear. I do not know if it influences, but the column is with Collation "utf8_general_ci". php search.:

 $response = array();

 require_once __DIR__ . '/db_connect.php';

 $db = new DB_CONNECT();
 $pesq = $_GET['pesq'];
 mysql_set_charset('utf8');

 mysql_query('SET CHARACTER SET utf8');
 $result = mysql_query("SELECT *FROM tabela WHERE titulo LIKE '%".$pesq."%'") or die(mysql_error());


 if (mysql_num_rows($result) > 0) {

$response["products"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $product = array();
    $product["pid"] = $row["pid"];
    $product["preco"] = $row["price"];
    $product["titulo"] = $row["titulo"];
    $product["uf"] = $row["uf"];
    $product["cidade"] = $row["cidade"];

    array_push($response["products"], $product);
}

$response["success"] = 1;

echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "Nenhum produto";

echo json_encode($response);
}

Return: inserir a descrição da imagem aqui

Table:

inserir a descrição da imagem aqui

  • I think this can help you: http://answall.com/questions/23105/json-n%C3%A3o-accept-accentuate%C3%A7%C3%A3o

5 answers

13

Instead of:

json_encode($response);

Use:

json_encode($response, JSON_UNESCAPED_UNICODE);

Or if you want not to "escape" the bars too:

json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

It is good to do this because the final file gets smaller.

See also: http://php.net/manual/en/json.constants.php


Let’s take a few examples:

$response = array(
    'a' => 'áéíóú -------- //'
);

echo json_encode($response);
// resultado: {"a":"\u00e1\u00e9\u00ed\u00f3\u00fa -------- \/\/"}

echo json_encode($response, JSON_UNESCAPED_UNICODE);
// resultado: {"a":"áéíóú -------- \/\/"}

echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
// resultado: {"a":"áéíóú -------- //"}

5

That’s not a problem, you agree with specification of JSON:

inserir a descrição da imagem aqui

In Javascript special characters can be used with Unicode escape codes (even in variable names!) in format \uNNNN, and JSON works the same way.

4

That is not a 'problem' to worry about, because the decode is responsible for converting the accent.

$array = array( 'nome' => 'Paição' , 'cidade' => 'São Paulo' );
$array = array_map( 'htmlentities' , $array );

//encode
$json = html_entity_decode( json_encode( $array ) );

//Output: {"nome":"Paição","cidade":"São Paulo"}
echo $json;

Example taken directly from DOC.

Online example on Ideone.

2

A simple solution would be to do this:

utf8_encode($texto);

This causes it to convert to utf8 and its string already has the correct accent.

0

Hello, I was having a lot of problems with this, until I decided to pay more attention to try a solution, until I assembled this small static class, I added in it a recursive conversion method of utf8 arrays that I found on the internet. Note the index of arrays CANNOT contain ACCENTS, since the values have no problems. Perhaps there is a more efficient solution, but it was only with this that I was able to solve my problem. Att

class JsonEncodePAcentos{

    #Coverte todo o array para utf8 de forma recursiva.
    private static function utf8_converter($array)
    { #Método obtido no site: http://nazcalabs.com/blog/convert-php-array-to-utf8-recursively/
        array_walk_recursive($array, function(&$item, $key){
            if(!mb_detect_encoding($item, 'utf-8', true)){
                    $item = utf8_encode($item);
            }
        });

        return $array;
    }


    public static function converter($arrayJson){       
        $arrayJson = self::utf8_converter($arrayJson);      
        $var = json_encode($arrayJson, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return utf8_decode($var);
    }

}


$array = array('Nome'=>'João da Silva Moreira', 'subArray'=>array('Ação', 'Cão', 'carateresEspeciais'=>'\\"'.'"'));

echo JsonEncodePAcentos::converter($array);


//{"Nome":"João da Silva Moreira","subArray":{"0":"Ação","1":"Cão","carateresEspeciais":"\\\"\""}}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.