PHP returns NULL when information has accents

0

When I want to display the data returned by a JSON, it returns me NULL . But when the database information is without accents, it returns me normally:

<?php
include_once 'WSAps_conexao.php';

$cidade =$_POST['cidade'];

$sql = $dbcon->query("SELECT * FROM parques WHERE Cidade = '$cidade'");

if(mysqli_num_rows($sql)>0)
{
    while($row = mysqli_fetch_assoc($sql))
    {
        $res[] = $row;
    }
    echo json_encode($res);
}
else
{
    echo "login_false";
        }

?>
    
asked by anonymous 26.11.2017 / 21:41

2 answers

3

This is because JSON encode only supports UTF-8 and probably your bank is in latin1, you can change the encoding as follows:

//Salva o charset padrão (só é necessário se for usar a conexão para outra coisa)
$charsetAnterior = db->get_charset()->charset;

//Define o charset para utf8
if (false === $mysqli->set_charset('utf8')) {
    printf('Error ao usar utf8: %s', $mysqli->error);
    exit;
}

$sql = $dbcon->query("SELECT * FROM parques WHERE Cidade = '$cidade'");

if(mysqli_num_rows($sql) > 0)
{
    while($row = mysqli_fetch_assoc($sql))
    {
        $res[] = $row;
    }
    echo json_encode($res);
} else {
    echo "login_false";
}

//Restaura o charset
if (false === $mysqli->set_charset($charsetAnterior)) {
    printf('Error ao usar %s: %s', $charsetAnterior, $mysqli->error);
    exit;
}
    
26.11.2017 / 21:55
0

The php returns correctly, the json_encode that transforms into null because it is not in utf-8. Here is another solution:

Before returning you call a function to convert the array to utf-8

$result = converteArrayParaUtf8($result); //chama a função
return json_encode($result); //retorna

function:

function converteArrayParaUtf8($result){
    array_walk_recursive($result, function(&$item,$key){
         if (!mb_detect_encoding($item, 'utf-8', true)) {
                $item = utf8_encode($item);
            }
    });
    return $result;
}
    
20.03.2018 / 14:32