Json_econde error parsing special characters coming from the database ( using mysql PDO)

Asked

Viewed 241 times

0

In a bank table there are accented words or words with c. When using json_encode in php to send the result to the view, json breaks due to the parser error. How best to handle these characters before calling json_encode?

Example of how it returns from the database. These objects should be parsed for json.

 [0] => Array
        (
            [usuario_nome] => Oliveira Souza
        )

    [1] => Array
        (
            [usuario_nome] => jão çávão
        )

    [2] => Array
        (
            [usuario_nome] => joao josjdsojd 
        )

I was able to pass the data the following way:

$sth = $conn->query("SELECT * FROM v_usuarios  where usuario_ativo = 'S' $condicao order by usuario_nome ASC");
    $sth->execute();
    $datas = array();

    while($data = $sth->fetchAll(PDO::FETCH_ASSOC))
    array_push($datas,json_encode($data, JSON_UNESCAPED_UNICODE));



$retorno =new Response(($datas[0]));
$retorno->headers->set('Content-Type','application/json; charset=utf-8');
return $retorno;

But there would be some better way?

  • Have you used JSON_UNESCAPED_UNICODE? http://answall.com/questions/120802/php-retorna-json-nulo-quando-tem-acento-no-mysql, http://answall.com/questions/155609/json-php-e-mysql/155624#155624, http://answall.com/questions/100008/howto allow accentuate%C3%A7%C3%A3o-em-json-utilizando-php/100014#100014, http://answall.com/questions/179183/problema-com-json-encode/179186#179186,

  • yes...and made the same mistake.

  • when I did this the result was: Error: JSON.parse: Unexpected non-whitespace Character after JSON data at line 1 column 483 of the JSON data

  • Have you tried PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8'?

1 answer

-1

Buddy, I’ve had enough of these problems and it’s not easy to solve, but I’ll try to help you.

function utf8_converter($array)
{
array_walk_recursive($array, function(&$item, $key){
    if(!mb_detect_encoding($item, 'utf-8', true)){
            $item = utf8_encode($item);
    }
});

return $array;
}

In this method, you call and place your array within the parameter it loops its array through each element and converts to UTF-8. Most of the time it can work, but there are exceptions. I hope I’ve helped.

Browser other questions tagged

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