json_encode 不适用于数组

Mas*_*man 0 php arrays json

我正在使用 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);
Run Code Online (Sandbox Code Playgroud)

这是代码。的json_encode效果rows[0]很好。但是,当我将其注释掉并尝试对 执行相同操作时rows,它什么也没有返回。

它甚至没有返回错误,它执行得很好,只是json_encode当我尝试使用rows.

我究竟做错了什么?

Mas*_*man 7

回答这个问题是为了防止有类似问题的可怜人发现这个问题。首先,事实print_r证明,json_last_error它对于了解问题所在非常有帮助。

首先,检查json_last_error()返回的值,并将其与此处的错误列表进行比较。如果返回的数字是5,请尝试使用该函数检查数组的值print_r。如果你看到一些奇怪的字符,很可能是数据库的编码有误。

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