我使用MySQL来存储数据库中的项目列表,我正在尝试从单个表中检索所有项目。连接部分工作正常,检索项目似乎运行良好,但我不能json_encode项目列表。
// Executes SQL query on the database specified by $con
$sql = "SELECT * FROM productlist";
$query = mysqli_query($con, $sql) or die(nl2br("\n Failed to execute query"));
// Retrieves all the rows returned by the SQL query
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows[0]); // test whether retrieval works
// Displays rows in content-type JSON and in PRETTY_PRINT
header('Content-Type: application/json');
echo json_encode($rows, JSON_PRETTY_PRINT);
这是代码。 json_encode
的{{1}}效果很好。但是,当我对其进行评论并尝试对rows[0]
执行相同操作时,它只会返回任何内容。
它甚至没有返回错误,它执行得很好,只是rows
函数在我使用json_encode
进行尝试时根本没有返回任何内容。
我做错了什么?
答案 0 :(得分:2)
在设置标题之前,您无法输出内容。除非您使用输出缓冲区(visual.exportData(models.ExportDataType.Summarized /* can be Underlying */, numOfRows)
.then(function (data) {
Log.log(data);
})
.catch(function (errors) {
Log.log(errors);
});
函数):
ob_
或者您可以更改脚本中的顺序:
ob_start();
echo json_encode($rows[0]);
header('Content-Type: application/json');
echo json_encode($rows, JSON_PRETTY_PRINT);
ob_end_flush();
最后一个选项可能会导致JSON解析错误,因为您在这里输出了两个“对象”。
您提到的header('Content-Type: application/json');
echo json_encode($rows[0]);
echo json_encode($rows, JSON_PRETTY_PRINT);
error是关于UTF-8编码的。你可以尝试对你的json进行utf8编码和解码。
json_last_error
如果这不能解决问题,您可能需要check if everything else is UTF-8 encoded。
答案 1 :(得分:1)
如果有类似问题的可怜的灵魂发现这个问题,请回答这个问题。
首先,print_r
和json_last_error
被证明对于了解问题是非常有用的。
首先,检查json_last_error()
返回的值,并将其与the list of errors here进行比较。如果返回的数字是5
,请尝试使用print_r
函数检查数组的值。如果你看到一些奇怪的字符,那么概率就是数据库有一些错误的编码。
就我而言,将某些列从latin
更改为utf-8
可以解决问题。
答案 2 :(得分:0)
试试这个:
echo "<pre>";
print_r(json_encode($rows, JSON_PRETTY_PRINT));
echo "</pre>";
答案 3 :(得分:-2)
首先,我要感谢,因为我通过此主题解决了“大”问题。我的页面空白,很难理解为什么。
如何检测:
echo json_encode($yourresult) ;
json_last_error($yourresult) ;
// if the error is 5, it is UTF-8 issue
如何使用PHP 7.2进行临时纠正:
echo json_encode($yourresult,JSON_INVALID_UTF8_IGNORE);
//wrong chars will be deleted