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

0

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

Example of how to return from the bank. 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 as follows:

$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 would there be any better way?

    
asked by anonymous 31.01.2017 / 01:42

1 answer

0

My friend, I've had a lot of these problems and it's not easy to solve it, 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, by calling and placing your array inside the parameter, it loopes through your array and converts to UTF-8. Most of the time it can work, but there are exceptions. I hope I have helped.

    
15.02.2017 / 20:58