简体   繁体   中英

Convert PHP Array to JSON object with UTF-8

I have the following PHP code which pulls the data form mysql (unicode entries)

$conn = mysqli_connect("localhost", "root", "", "mapping") or die ("Error".mysqli_error($conn));
mysqli_set_charset($conn,"utf8");
$sql = "select * from villages";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
    $myArray[] = $row;
}
mysqli_close($conn);

echo json_encode($myArray, JSON_UNESCAPED_UNICODE);

?>

$myArray[0] is:

{"id":"1","village":"अकबरपुर","villageEn":"akbarpur","subdiv":"हुजूर","tehsil":"हुजूर","ricircle":"रातीबढ़","patwarih":"अकबरपुर"}

When I do console.log() all the array items are shown in at once, what I want is to view them as objects[javascript (aka JSON)] in browser devtools

if you want to use the json in javascript you can simply do that:
(I suppose you call that php file directly, not via an ajax call!)

<?php
$conn = mysqli_connect("localhost", "root", "", "mapping") or die ("Error".mysqli_error($conn));
mysqli_set_charset($conn,"utf8");
$sql = "select * from villages";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
   $myArray[] = $row;
}
mysqli_close($conn);

?>
<script>
// here's the trick!
var villages = <?php echo json_encode($myArray, JSON_UNESCAPED_UNICODE); ?>;
console.log(villages);
</script>

If you use it via an ajax call check out @julekgwa's answer!

use JSON.parse() in your javascript (using jQuery ).

//assuming that you are using ajax
$.post('get_villages.php', function(data) {
   var villages = JSON.parse(data);
   for (var village in villages) {
       console.log(village.id + ' ' + village.village + ' ' + village.villageEng);
   }
});

Try this one to print in browser devtools :

$myArray = json_encode($myArray, JSON_UNESCAPED_UNICODE);
echo 'village : '.$myArray['village'];
echo 'subdiv : '.$myArray['subdiv'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM