Am trying to retrieve some array from mysql database in json format but for some reasons it returning string value even after using json_encode and adding headers to the PHP script here is the php script am using
<?php
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json; charset: UTF-8");
header("Access-Control-Allow-Methods: GET");
include_once("db.php");
$db = new Database();
$conn = $db->connect();
$sql = "SELECT * FROM tbl_nn";
if ($conn->query($sql)) {
$res = mysqli_query($conn, $sql);
$outp = array();
while($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data['image'] = $rs['image'];
$outp[] = $data;
}
echo json_encode($outp);
} else {
echo "Connection Failed" . $conn->error;
}
My current output
[{"image":"img1"},{"image":"img2"},{"image":"img3"}]
Expected Result
[
{
"image": "img1"
},
{
"image": "img2"
},
{
"image": "img3"
}
]
CodePudding user response:
try this:
echo json_encode($outp,true);
or this:
$array = json_decode($string,true)
CodePudding user response:
Found a solution dropping it here in case someone(a newbie like me) might need this so turns out the bug was cause by the include php tag so here is the correction
Old code
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json; charset: UTF-8");
header("Access-Control-Allow-Methods: GET");
include_once("db.php");
$db = new Database();
$conn = $db->connect();
New Corrected Code
include_once("db.php");
$db = new Database();
$conn = $db->connect();
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json; charset: UTF-8");
header("Access-Control-Allow-Methods: GET");