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:
3 Answers 3
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);
1 Comment
Add header('Content-Type: application/json', true); to your code before echo json_encode () to set the correct mime type.
The other error messages from the validator website are curious; i cannot see invalid characters or fields that are not wrapped in double quotes. Maybe, the validator website has some bugs.
3 Comments
<!-- Hosting24 Analytics Code --> <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script> <!-- End Of Analytics Code -->; this invalidates your json output. Can you disable this behavior in your server settings?add header in php file..
header("Content-Type: application/json; charset=UTF-8");