1

When I try to encode on a JSON a query from MySQL database that gives me a null JSON when the words have accents eg. " olá " , " à " etc

my php code:

$sql = "SELECT `name`
          FROM `login`
         WHERE `id`='1';";

$result = mysqli_query($conn, $sql);
     
$emparray = array();
while($row = mysqli_fetch_assoc($result)){
    $emparray[] = $row;
}
echo json_encode($emparray,JSON_UNESCAPED_UNICODE);

my database:

id  |  name | 
1   |  Olá  |
Dharman
  • 30,962
  • 25
  • 85
  • 135
Dariko77
  • 141
  • 1
  • 8
  • What version php are you using? The `JSON_UNESCAPED_UNICODE` constant was added in php 5.4 meaning if you are on an older version `json_encode` would return null and throw a notice (undefined constant) and warning (invalid argument) errors. Outside of that, I don't see an issue with the code (https://3v4l.org/HqIvU) so I would start with the usual, check the error logs. – Jonathan Kuhn Aug 30 '16 at 18:36
  • Which encoding and collation are you using for table "login"? Did you try to fill $emparray manually from PHP? – Ondřej Šotek Aug 30 '16 at 18:46
  • my php version is 5.6.23 – Dariko77 Aug 30 '16 at 18:53
  • step one: [ensure you are utf-8 all the way down](http://stackoverflow.com/a/279279/740553). Don't expect encoding compatibiliy to work without explicitly telling everything *exactly* what you need. – Mike 'Pomax' Kamermans Aug 30 '16 at 19:30
  • @JonathanKuhn: terminology: json doesn't "throw" anything. it issues a notice. none of PHP's procedural functions will ever throw anything. – Marc B Aug 30 '16 at 19:55

2 Answers2

1

json_encode assumes that the result is encoded in UTF-8, if it is not returned null

first verify that your database server is configured with UTF_8

or add the set_charset before the consultation

mysqli_set_charset($conn,"utf8");

Use header to modify the HTTP header, UTF-8 all the way through

header('Content-Type: text/html; charset=utf-8');
Community
  • 1
  • 1
Dev. Joel
  • 1,127
  • 1
  • 9
  • 14
-1

Its working fine check Click Here

<?php
 echo json_encode("Olá ",JSON_UNESCAPED_UNICODE);
?>
Abhijit Jagtap
  • 2,740
  • 2
  • 29
  • 43