Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php returns invalid json

Tags:

json

arrays

php

The following php code returns an invalid json error not sure why

<?php
include("dbConnect.php");

$sql = "SELECT QID, Question, Answer,CatID FROM Questions";


$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('qid'=>$row[0],
'question'=>$row[1],
'answer'=>$row[2],
'catid'=>$row[3]
));
}

echo json_encode(array("result"=>$result));

mysqli_close($con);

when I run the link to the php it returns this data:

{"result":[{"qid":"1","question":"Question 1","answer":"Answer 1","catid":"1"},{"qid":"2","question":"Question 2","answer":"Answer 2","catid":"2"},{"qid":"3","question":"Question 3","answer":"Answer 3","catid":"3"},{"qid":"4","question":"Question 4","answer":"Answer 4","catid":"1"},{"qid":"5","question":"Question 5","answer":"Answer 5","catid":"3"},{"qid":"6","question":"Question 6","answer":"Answer 6","catid":"3"}]} 

and I tried running the link to the php that returns the json data using this json formatter website

I get these errors:

Error:Invalid media type, expecting application/json.[Code 28, Structure 0]

Error:Invalid encoding, expecting UTF-8, UTF-16 or UTF-32.[Code 29, Structure 0]

Error:Strings should be wrapped in double quotes.[Code 17, Structure 114]

Error:Invalid characters found.[Code 18, Structure 114]

Error:Strings should be wrapped in double quotes.[Code 17, Structure 116]

Error:Invalid characters found.[Code 18, Structure 116]

If I try copying the resulting json data I get a valid JSON format but when I try running it from the php link that is stored on my server I get the above errors

UPDATE:

link to php

like image 901
u_kami Avatar asked Jun 08 '26 18:06

u_kami


1 Answers

The problem isn't the JSON string, it's the header data. You must specify the Content-Type header manually, otherwise it will send the output as text/html:

<?php
include("dbConnect.php");

$sql = "SELECT QID, Question, Answer,CatID FROM Questions";


$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('qid'=>$row[0],
'question'=>$row[1],
'answer'=>$row[2],
'catid'=>$row[3]
));
}

header("Content-Type: application/json; charset=utf-8");
echo json_encode(array("result"=>$result));

mysqli_close($con);
like image 66
Manulaiko Avatar answered Jun 10 '26 09:06

Manulaiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!