0

I've got this code that I use to populate a select with an ajax call from another php page:

$id = $_GET["id"];
$sql = "SELECT town_name, 
               town_code 
        FROM   tbtown 
        WHERE  area_id = '$id' 
        ORDER BY town_name";
$result = mysqli_query($conn, $sql);
$arr = array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
    $arr[] = $row;
}
echo json_encode($arr);

Some town_name column values, contains characters like è ì and I found that in those cases the json_encode() function set that value to NULL.

I find out also that htmlentities() function applied to every array value solve the problem.

I wonder if there is a simple way to apply htmlentities() to the entire array.

kiks73
  • 3,718
  • 3
  • 25
  • 52
  • http://php.net/manual/en/function.array-walk-recursive.php – ceejayoz Apr 16 '15 at 13:40
  • 1
    `json_encode('ì')` results in `"\u00ec"` so there must be something else going on. You should fix that instead of trying to patch it up. Take a look at for example http://stackoverflow.com/questions/279170/utf-8-all-the-way-through – jeroen Apr 16 '15 at 13:47
  • mySql collation was Latin1_Swdish, but also changing it to utf8mb4 values are set to null. – kiks73 Apr 16 '15 at 14:03

2 Answers2

1

You can use array_walk_recursive for this.

array_walk_recursive($arr, function(&$item, $key) {
    $item = htmlentities($item);
});
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

try this one,

echo json_encode($arr, JSON_UNESCAPED_UNICODE);
Danny
  • 793
  • 1
  • 9
  • 20