【问题标题】:php json_encode not working on arrays partiallyphp json_encode 部分不适用于数组
【发布时间】:2013-11-28 18:18:19
【问题描述】:

我有一个 PHP 代码需要将 DB 表数据编码为 json。 所以我使用了 json_encode()。

我使用这里给出的表格 - http://www.geekality.net/2011/08/21/country-names-continent-names-and-iso-3166-codes-for-mysql/

对于不同的输入,这段代码的行为似乎有所不同。

查询 - $query = "SELECT * FROM countries "; 不返回任何 json 值。

查询 -$query = "SELECT * FROM countries where continent_code='AS'"; 正确返回 json 值。

$query = "SELECT * FROM countries where continent_code='EU'"; 也不返回任何内容。

同样,'NA','AF' 没有工作,而其他工作完美。

我对 PHP 的 json_encode 的这种行为感到奇怪。

这是我的代码。

<?php
$con=mysqli_connect('localhost','xxxx','xxxxx','joomla30');
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM countries where continent_code='EU'") or die (mysqli_error($con));

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
      $orders[] = array(
          'CountryCode' => $row['code'],
          'CountryName' => $row['name']
          );
  }
//print_r($orders);

echo json_encode($orders);

mysqli_close($con);
?>

直到上一行json_encode,才携带数据。所以我认为它的json编码问题。

我尝试使用 print_r($orders); 了解它。
我从中得到了以下输出。

如果我尝试使用“EU”,我会得到这个数组。

Array ( [0] => Array ( [CountryCode] => AD [CountryName] => Andorra ) 
[1] => Array ( [CountryCode] => AL [CountryName] => Albania ) 
[2] => Array ( [CountryCode] => AT [CountryName] => Austria ) 
[3] => Array ( [CountryCode] => AX [CountryName] => Åland Islands )...

如果我尝试'AS',我会得到这个数组。

Array ( [0] => Array ( [CountryCode] => AE [CountryName] => United Arab Emirates ) 
[1] => Array ( [CountryCode] => AF [CountryName] => Afghanistan) 
[2] => Array ( [CountryCode] => AM [CountryName] => Armenia) 
[3] => Array ( [CountryCode] => AZ [CountryName] => Azerbaijan)...

这两个数组看起来都差不多... 但 Json_encode 仅适用于 'AS' 而不适用于 'EU'。

有谁知道如何解决这个问题? 如果是这样,请告诉我..

【问题讨论】:

  • 我猜,问题出在“奥兰群岛”,因为 json_encode 的“Å”有问题,因为它是一个奇怪的 unicode。尝试将 mysql_connection 设置为 UTF-8

标签: php json


【解决方案1】:

您应该确保 Web 应用程序的每个组件都使用 UTF-8。 This answer 来自另一个问题将告诉你如何做到这一点。如果你 read this 来自 RFC4627:

编码:JSON 文本应以 Unicode 编码。默认编码为 UTF-8。

json_encode 函数要求所有传入数据都采用 UTF-8 编码。这就是为什么 Åland Islands 之类的字符串可能会给您带来问题。

【讨论】:

  • 感谢您在 2 分钟内的快速回复。我添加了 mysqli_set_charset($con, 'utf8'); 效果很好...
【解决方案2】:

这里只是一个随机猜测:json_encode 要求您输入的所有数据都是 UTF-8 编码,否则它将失败。在这些失败的国家/地区,您可能拥有包含非 ASCII 字符的数据。纯 ASCII 恰好与 UTF-8 兼容,您需要特别注意的非 ASCII 字符。请参阅 UTF-8 all the way through 了解如何从数据库中获取 UTF-8 编码数据(使用 mysqli_set_charset)。

【讨论】:

  • 谢谢,我刚刚在我准备好的声明中添加了以下代码$db-&gt;set_charset("utf8"); 并且可以完美运行
猜你喜欢
  • 2012-07-29
  • 2015-05-03
  • 2018-10-10
  • 2020-11-20
  • 2014-01-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2018-09-05
相关资源
最近更新 更多