Php returns null JSON when it has accent in Mysql

Asked

Viewed 3,267 times

0

Hello, I have the following code in php:

<?php
   $con=mysqli_connect("localhost","user","senha","banco");
   $parametro = $_GET["parametro"];
   if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " .mysqli_connect_error(); }
   $sql = "SELECT * FROM " . $parametro;

   if ($result = mysqli_query($con, $sql))
   {
        $resultArray = array();
        $tempArray = array();

    while($row = $result->fetch_object())
    {
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }
    echo json_encode($resultArray);
}
mysqli_close($con);
?>

It returns a JSON with a table of the Mysql server whose name was passed by the parameter, but when it has an accent or a "ç" for example it returns null Mysql is accepting the accent, I can check it by phpmyadmin, the problem is even in php. For a table cities it returns this:

[{"id":"1","nome":"Porto Alegre","estado":"RS"},{"id":"2","nome":"Rio de janeiro","estado":"RJ"},{"id":"3","nome":null,"estado":"SP"}]

Where São Paulo should be he returns null

I have tried using json_encode with JSON_UNESCAPED_UNICODE constant to encode characters literally instead of escaping them.

echo json_encode($resultArray, JSON_UNESCAPED_UNICODE);

but this error appears: Warning: json_encode() expects exactly 1 parameter, 2 given in /home/diretorio/public_html/busca.php on line 24

how to solve this?

5 answers

1


Simplest solution found is to add these two lines:

$str = str_replace('\u','u',$decoded);
$strJSON = preg_replace('/u([\da-fA-F]{4})/', '&#x\1;', $str);

Stay tuned to your PHP version, because I use 5.5 and in the tests I did not have this problem! My tests were like this:

echo json_encode($json, JSON_UNESCAPED_UNICODE);

[{"id":"1","name":"Porto Alegre","state":"RS"},{"id":"2","name":"Rio of January","state":"RJ"},{"id":"3","name":"SANE Paulo","state":"SP"}]

echo json_encode($json);

[{"id":"1","name":"Porto Alegre","state":"RS"},{"id":"2","name":"Rio of January","state":"RJ"},{"id":"3","name":"S u00e3o Paulo","state":"SP"}]

  • But how do I turn "S u00e3o Paulo" into "São Paulo"? I put <!DOCTYPE html>&#xA;<head>&#xA;<meta charset="UTF-8">&#xA;</head> but still didn’t give @Jhonnyjks

  • 1

    Dude, it would be best to update your php to at least 5.4.0, which will then accept the JSON_UNESCAPED_UNICODE parameter, or you should find some function that decodes from utf8, but conventional ones didn’t work here.

  • These two lines have now solved: $str = str_replace(' u','u',$decoded); $strJSON = preg_replace('/u([ da-fa-F]{4})/', '&#x 1;', $str); I found it at: http://stackoverflow.com/a/20181671/5664531

1

Try something like that:

<?php
       $con=mysqli_connect("localhost","user","senha","banco");
       $parametro = $_GET["parametro"];
       if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " .mysqli_connect_error(); }
       $sql = "SELECT * FROM " . $parametro;

       if ($result = mysqli_query($con, $sql))
       {

        while($row = $result->fetch_object())
        {
            foreach($row as $key => $col){
               $col_array[$key] = utf8_encode($col);
            }
            $row_array[] =  $col_array;

        }
        echo json_encode($row_array);
    }
    mysqli_close($con);
    ?>

0

A line before the echo json_encode($resultArray), put that:

$resultArray = array_map('utf8_encode', $resultArray);

0

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;
}

0

Friend, you can use the mb_convert_encoding function to convert the encoding

//In this case, assuming the standard is in ISO-8859-1 and you want UTF-8 mb_convert_encoding($utf8, 'UTF-8', 'ISO-8859-1');

  • I need to implement this function somewhere specific? pq I did some tests here and it still resulted in null @Duke

  • This is an internal function of PHP, it assumes that you know the encoding that the string is. Which encoding pattern is the table data ? You can also test with mb_strtolower( $Row, 'UTF-8'); for test. Do it there and put it here again.

Browser other questions tagged

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