PHP:json_encode()在多维数组中不显示任何内容 [英] PHP: json_encode() doesn't show anything with multidimensional array
问题描述
我正在尝试制作一个简单的PHP脚本,该脚本从MySQL数据库中获取一个表并将结果编码为JSON,以便以后可以在Java中使用它们.
I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
这是我的代码:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
这仅给出空白页作为输出(错误消息设置为显示).但是,如果我将 json_encode($ output)
更改为 json_encode($ output [0])
(或数组范围内的任何其他数字),输出将变成一个 $ row数组
.
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output)
to json_encode($output[0])
(or any other number within the array's bounds), the output becomes that one $row array
.
这可能是一个非常愚蠢的问题,但是经过大约3个小时的研究,我才机智.谢谢您的帮助.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
推荐答案
用户@Joni引导我提出了解决方案.
User @Joni led me to the solution.
添加 mysql_set_charset("utf8")
可以解决我的问题.
Adding mysql_set_charset("utf8")
fixed my issue.
如本文所提及:为什么对json_encode的此PHP调用无声地失败-无法处理单引号?.
这篇关于PHP:json_encode()在多维数组中不显示任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!