简体   繁体   中英

printing out a json array

I am trying to figure out how to print a json array. I am trying to handle this from Android code but it is not working. I believe the problem lies in how I am outputting json. the below doesn't show anything. The script is below:

<?php
// Create connection
$conn=mysqli_connect("localhost","dhdkahd","dsdajdsa","dsadjsajd");
$json = array();
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (!$conn->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $conn->error);
}


$sql='SELECT title, description, country, city, rate FROM discounts';

$rs=$conn->query($sql);

if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {

    /*$rs->data_seek(0);
    while($row = $rs->fetch_assoc()){
        echo $row['title'] . '<br>';
    }*/

    while ( $row = $rs->fetch_assoc() )
    {
        $json[] = json_encode($row,JSON_UNESCAPED_UNICODE);
    }
}
//echo json_decode($json);
echo json_encode($json);

mysqli_close($conn);
?>

thanks in advance

You can only call json_encode once . You're double-encoding everything.

The line where you're adding data to the array needs to be

    $json[] = $row;

Then, when the array is built up, you encode the entire thing in one single call:

echo json_encode($json);

You call json_encode twice. To fix it, change your code to:

if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {

    /*$rs->data_seek(0);
    while($row = $rs->fetch_assoc()){
        echo $row['title'] . '<br>';
    }*/

    while ( $row = $rs->fetch_assoc() )
    {
        $json[] = $row;
    }
}
//echo json_decode($json);
echo json_encode($json);

mysqli_close($conn);
?>

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