PHP returns NULL when information has accents

Asked

Viewed 275 times

0

When I want to display the data returned by a JSON, it returns to me NULL. Only 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";
        }

?>
  • Probably your database should not be encoded with UTF8 characters, try so: json_encode($res, JSON_UNESCAPED_UNICODE) and tell me if anything comes up when you try to return with the accents.

  • Still returning me NULL, my database is configured with utf8_general_ci

  • Try to use set_charset('utf8') also as Guilherme’s answer, you need to check if your PHP file is also in UTF8, and if the file that sends the information to your database is also in the same encoding. If you use the Notepad++ software, in the menu Formatar, You can check if the document is in the right encoding. It is good to check all the places where the information goes if it is in the same coding.

  • http://rmonte.com/acentuacao-no-php-e-mysql-com-utf-8/ This link explains a little about what I’m talking about, the commands are in Mysql, but it’s easy to switch to Mysqli. In the comments you have an example: http://rmonte.com/acentuaca-no-php-e-mysql-com-utf-8/#comment-1895

  • Thank you for the reply, I got by set_charset('utf8'), according to Guilherme’s reply

  • @Fernandovr only needs the files to be saved in utf8 and the header/charset if the accents are not escaped in json_encode, but as by default it "escapes", for example "ã" turns " u00e3" so there is no need, and at the time that use on Android (author case) he’ll probably use JSONobject (https://developer.android.com/reference/org/json/JSONObject.html), which will recognize the escaped accents and print normally.

  • I understand @Guilhermenascimento, but incredible as it seems I’ve had problems also with accentuation when the file I sent to the database, be in different encoding. It sent to the database in an encoding that the database saved in another one and when displaying the query there was a different result. As I do not know the system of the friend who asked, so sometimes it is good to check all the information path until you find where the error is.

  • Good @Patrickcamargo who turned out all right. Hugs ^^

Show 3 more comments

2 answers

3


This is because the JSON Encode only supports UTF-8 and probably your database is in latin1, you can exchange the encoding like this:

//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;
}
  • I made the change in the code, but it returns me "Parque de S u00e3o Paulo" instead of "Parque de São Paulo".

  • @Patrickcamargo Yes, this is correct, JSON accents are in this format to avoid loss of characters in the transmission, this is done by JSON_ENCODE itself and not by set_charset. But if you display JSON in a Modal in your android app you will notice that the accent will appear correctly.

  • 1

    Thanks man, I was testing by browser. I tested by android app and it worked, thank you very much

0

php returns correctly, the json_encode that turns null because it is not in utf-8. Here’s 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;
}

Browser other questions tagged

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