php json_encode 返回 NULL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1972006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:29:54  来源:igfitidea点击:

json_encode is returning NULL?

phpnulljson

提问by tarnfeld

For some reason the item "description" returns NULLwith the following code:

出于某种原因,项目“描述”返回NULL以下代码:

<?php
include('db.php');

$result = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 2') or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($result)){
    $rows[] = $row;
}

echo json_encode($rows);
?>

Here is the schema for my database:

这是我的数据库的架构:

CREATE TABLE `staff` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` longtext COLLATE utf8_unicode_ci,
  `description` longtext COLLATE utf8_unicode_ci,
  `icon` longtext COLLATE utf8_unicode_ci,
  `date` longtext COLLATE utf8_unicode_ci,
  `company` longtext COLLATE utf8_unicode_ci,
  `companyurl` longtext COLLATE utf8_unicode_ci,
  `appurl` longtext COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Here is what is echoed out on the page:

这是页面上的回声:

[{"id":"4","name":"Noter 2","description":null,"icon":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","date":"1262032317","company":"dBelement, LLC","companyurl":"http:\/\/dbelement.com\/","appurl":"http:\/\/noter2.dbelement.com"},{"id":"3","name":"Noter 2","description":null,"icon":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","date":"1262032317","company":"dBelement, LLC","companyurl":"http:\/\/dbelement.com\/","appurl":"http:\/\/noter2.dbelement.com"}]

Any ideas?

有任何想法吗?

回答by ntd

I bet you are retrieving data in non-utf8 encoding: try to put mysql_query('SET CHARACTER SET utf8')before your SELECTquery.

我敢打赌,您正在以非 utf8 编码检索数据:尝试放在查询mysql_query('SET CHARACTER SET utf8')之前SELECT

回答by K. Norbert

If you have at least PHP 5.5, you can use json_last_error_msg(), which will return a string describing the problem.

如果你至少有 PHP 5.5,你可以使用json_last_error_msg(),它会返回一个描述问题的字符串。

If you don't have 5.5, but are on/above 5.3, you can use json_last_error()to see what the problem is.

如果您没有 5.5,但在 5.3 上/在 5.3 以上,您可以使用json_last_error()来查看问题所在。

It will return an integer, that you can use to identify the problem in the function's documentation. Currently (2012.01.19), the identifiers are:

它将返回一个整数,您可以使用它来识别函数文档中的问题。目前(2012.01.19),标识符是:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

These can change in future versions, so it's better to consult the manual.

这些在将来的版本中可能会发生变化,因此最好查阅手册。

If you are below 5.3, you are out of luck, there is no way to ask what the error was.

如果您低于 5.3,那么您就不走运了,无法询问错误是什么。

回答by Pablo Abdelhay

ntd's anwser didn't solve my problem. For those in same situation, here is how I finally handled this error: Just utf8_encode each of your results.

ntd 的 anwser 没有解决我的问题。对于那些处于相同情况的人,这是我最终处理此错误的方式:只需 utf8_encode 您的每个结果。

while($row = mysql_fetch_assoc($result)){
    $rows[] = array_map('utf8_encode', $row);
}

Hope it helps!

希望能帮助到你!

回答by Ivo Urbanek

few day ago I have the SAME problem with 1 table.

几天前,我在 1 张桌子上遇到了同样的问题。

Firstly try:

首先尝试:

echo json_encode($rows);
echo json_last_error();  // returns 5 ?

If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.

如果最后一行返回 5,则问题出在您的数据上。我知道,你的表是 UTF-8,但没有输入数据。例如,输入是在 txt 文件中,但在 Win 机器上使用愚蠢的编码(在我的情况下为 Win-1250 = CP1250)创建,并且此数据已输入到数据库中。

Solution? Look for new data (excel, web page), edit source txt filevia PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.

解决方案?查找新数据(excel,网页),通过 PSPad(或其他任何方式)编辑源 txt 文件将编码更改为 UTF-8,删除所有行,现在从原始数据中放入数据。节省。进入数据库

You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...

您也可以只将编码更改为 utf-8,然后手动更改所有行(为 cols 提供特殊字符 - desc,...)。对奴隶好...

回答by koder

You should pass utf8 encoded string in json_encode. You can use utf8_encodeand array_map()function like below:

您应该在 json_encode 中传递 utf8 编码的字符串。您可以使用utf8_encodearray_map()功能如下:

<?php
    $encoded_rows = array_map('utf8_encode', $rows);
    echo json_encode($encoded_rows);
?>

回答by bejs

The PHP.net recommended way of setting the charset is now this:

PHP.net 推荐的设置字符集的方法现在是这样的:

mysqli_set_charset('utf8')

mysqli_set_charset('utf8')

回答by mpen

AHHH!!! This looks so wrong it hurts my head. Try something more like this...

啊啊啊!!!这看起来太错误了,它让我头疼。尝试更像这样的东西......

<?php
include('db.php');

$result = mysql_query('SELECT `id`, `name`, `description`, `icon` FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($result)){
    $rows[] = $row;
}

echo json_encode($rows);
?>
  • When iterating over mysql_num_rowsyou should use <not <=. You should also cache this value (save it to a variable) instead of having it re-count every loop. Who knows what it's doing under the hood... (might be efficient, I'm not really sure)
  • You don't need to copy out each value explicitly like that... you're just making this harder on yourself. If the query is returning more values than you've listed there, list only the ones you want in your SQL.
  • mysql_fetch_arrayreturns the values both by keyand by int. You not using the indices, so don't fetch em.
  • 迭代时,mysql_num_rows您应该使用<not <=。您还应该缓存这个值(将它保存到一个变量中),而不是让它在每个循环中重新计数。谁知道它在幕后做什么......(可能很有效率,我不太确定)
  • 你不需要像那样明确地复制每个值......你只是让自己更难。如果查询返回的值多于您在此处列出的值,请仅列出您希望在 SQL 中使用的值。
  • mysql_fetch_array返回值 bykey和 by int。你没有使用索引,所以不要获取它们。

If this really is a problem with json_encode, then might I suggest replacing the body of the loop with something like

如果这确实是一个问题json_encode,那么我是否建议将循环体替换为类似的东西

$rows[] = array_map('htmlentities',$row);

Perhpas there are some special chars in there that are mucking things up...

Perhpas 那里有一些特殊的字符正在把事情搞砸......

回答by MichaelS

For anyone using PDO, the solution is similar to ntd's answer.

对于使用 PDO 的任何人,解决方案类似于ntd's answer

From the PHP PDO::__construct page, as a comment from the user Kiipa at live dot com:

来自PHP PDO::__construct 页面,作为来自live dot com用户Kiipa的评论:

To get UTF-8 charset you can specify that in the DSN.

$link = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");

要获得 UTF-8 字符集,您可以在 DSN 中指定它。

$link = new PDO("mysql:host=localhost;dbname=DB; charset=UTF8");

回答by Victor S

For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializableon entities.

对我来说,json_encode 会返回实体的空编码的问题是因为我的 jsonSerialize 实现获取了相关实体的整个对象;我通过确保获取相关/关联实体的 ID 并在有多个实体与要 json 序列化的对象关联时调用 ->toArray() 来解决该问题。请注意,我说的是implements JsonSerializable实体上的情况。

回答by Laci

I had the same problem and the solution was to use my own function instead of json_encode()

我遇到了同样的问题,解决方案是使用我自己的函数而不是json_encode()

echo '["' . implode('","', $row) . '"]';