PHP返回无效的JSON [英] php returns invalid json

查看:108
本文介绍了PHP返回无效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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"}]} 

,我尝试使用此 json格式化程序网站

我得到这些错误:

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链接运行它时,会出现上述错误

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

更新:

链接到php

推荐答案

问题不是JSON字符串,而是标题数据. 您必须手动指定Content-Type标头,否则它将以text/html格式发送输出:

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

这篇关于PHP返回无效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆