PHP 返回无效的 JSON


php returns invalid json

以下 php 代码返回无效的 json 错误,不知道为什么

<?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);

当我运行指向 php 的链接时,它会返回以下数据:

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

我尝试使用此 json 格式化程序网站运行指向返回 json 数据的 php 的链接

我收到这些错误:

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]

如果我尝试复制生成的 json 数据,我会得到有效的 JSON 格式,但是当我尝试从存储在服务器上的 php 链接运行它时,我收到上述错误

更新:

链接到 PHP

问题不在于 JSON 字符串,而在于标头数据。您必须手动指定 Content-Type 标头,否则它将以 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);

> 在echo json_encode ()之前将header('Content-Type: application/json', true);添加到代码中以设置正确的 MIME 类型。

来自验证器网站的其他错误消息很奇怪;我看不到未用双引号括起来的无效字符或字段。也许,验证器网站有一些错误。

php文件中添加标头。

header("Content-Type: application/json;字符集=UTF-8");