json_encode不适用于数组

问题描述 投票:0回答:4

我正在使用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_encoderows[0]运作良好。但是,当我注释掉并尝试对rows执行相同操作时,它什么也没有返回。

甚至都没有返回错误,它执行得很好,只是当我用json_encode进行尝试时,rows函数根本不返回任何内容。

我在做什么错?

php arrays json
4个回答
2
投票

设置标题之前,您无法输出任何内容。除非您使用输出缓冲区(ob_功能):

ob_start();
echo json_encode($rows[0]);
header('Content-Type: application/json');
echo json_encode($rows, JSON_PRETTY_PRINT);
ob_end_flush();

或者您可以在脚本中更改顺序:

header('Content-Type: application/json');
echo json_encode($rows[0]);
echo json_encode($rows, JSON_PRETTY_PRINT);

由于您在此处输出两个“对象”,因此最后一个选项可能会导致JSON解析错误。

您提到的json_last_error error与UTF-8编码有关。您可以尝试utf8编码和解码json。

json_encode($rows, JSON_UNESCAPED_UNICODE);
json_decode($json, false, 512, JSON_UNESCAPED_UNICODE);

如果这不能解决问题,则可能需要check if everything else is UTF-8 encoded


2
投票

为一个有类似问题的可怜人找到这个问题,请回答这个问题。首先,print_rjson_last_error被证明在了解问题出在哪里方面非常有用。

首先,检查json_last_error()返回的值,并将其与the list of errors here进行比较。如果返回的数字为5,请尝试使用print_r函数检查数组的值。如果看到一些奇怪的字符,则很可能是数据库编码错误。

就我而言,将某些列从latin更改为utf-8解决了该问题。


-1
投票

尝试一下:

echo "<pre>";
print_r(json_encode($rows, JSON_PRETTY_PRINT));
echo "</pre>";

-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
© www.soinside.com 2019 - 2024. All rights reserved.