json_encode回显空白。可能的utf 8问题?

时间:2016-02-18 06:04:12

标签: php arrays json

我不知道如何调试这个。我从数据库中获取一个数组,该数组返回正常,但是当我尝试在其上使用json_encode时,它返回空白。任何帮助表示赞赏。

<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "username";
$password = "password";
mysql_connect($servername, $username, $password) or die(mysql_error());
mysql_select_db("places") or die(mysql_error());
$result = mysql_query("SELECT Location, Latitude, Longitude FROM places WHERE Latitude IS NOT NULL GROUP BY Location, Latitude, Longitude");
$places = array();
while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
    $places[] = $row;
}
$json = json_encode($places, JSON_UNESCAPED_UNICODE);
echo $json;
?>

在places []中返回的内容的示例是:

Array
(
[0] => Array
    (
        [0] => testPlace1
        [1] => 50.1019
        [2] => -75.0263
    )

[1] => Array
    (
        [0] => testPlace2
        [1] => 130.4834
        [2] => 48.3428
    )

[2] => Array
    (
        [0] => testPlace3
        [1] => 23.3003
        [2] => -48.3201
    )
...
....

然后继续。有一些在其中有unicode字符,虽然这是我的初始,所以我在php代码中添加了一些内容来帮助,但我不确定它是否正确。

3 个答案:

答案 0 :(得分:2)

问题是您使用了两次json_encode。你不能json_encode已经是一个json字符串。

另请注意,不推荐使用这些mysql函数。我建议你使用PDO。

<强>更新

显然,你在位置有一些特殊的字母。您可以通过这种方式将它们编码为utf8:

$places = array_map(function($place) {
    $place[0] = utf8_encode($place[0]);
    return $place;
}, $places );

对于JSON_UNESCAPED_UNICODE,解码json后,unicode转义符将映射到相应的UTF-8字符串。因此,您通常不需要它。

答案 1 :(得分:1)

如果出现utf8问题,您可以使用charset进行数据库连接

$connection = mysqli_connect($servername, $username, $password);
mysqli_set_charset($connection,'utf8');

答案 2 :(得分:0)

你的守则是正确的。 我刚检查过它。我以http://jsonlint.com/的格式以上述格式获得了json输出,它是有效的。

[[\"Test1\",\"50.1019\",\"-75.0263\"],[\"testPlace2\",\"130.4834\",\"48.3428\"]]

与此类似,您只需运行代码并检查您的json输出: http://jsonlint.com/它可能对你有帮助。