JSON accent

5

I'm having an accent problem when I start JSON. If I use characters like ã, õ, ô, ç, some codes appear. I do not know if it influences, but the column is Collation "utf8_general_ci". search.php :

 $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 :

Table:

    
asked by anonymous 25.05.2015 / 21:15

5 answers

8

Instead of:

json_encode($response);

Use:

json_encode($response, JSON_UNESCAPED_UNICODE);

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

json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

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

See also: link

Here are some 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":"áéíóú -------- //"}
    
30.05.2015 / 00:01
5

This is not a problem, it complies with the JSON specification :

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

    
25.05.2015 / 22:45
4

This is not a 'problem' to worry about, as decode will translate 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 straight from DOC .

Example online at Ideone .

    
25.05.2015 / 22:37
2

A simple solution would be to do this:

utf8_encode($texto);

This causes it to convert to utf8 and its string is already accented correctly.

    
25.05.2015 / 21:25
0
Hello, I was having a lot of problems with this, until I decided to give more attention to try a solution, until I mounted this small static class, I added a method of recursive conversion of arrays to utf8 that I found on the internet. Attention the index of the arrays can not contain ACCENTS, since the values have no problems. Maybe 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":"\\"\""}}
    
21.09.2017 / 17:51