json_encode 返回 NULL?

发布于 2024-08-15 18:43:14 字数 1462 浏览 3 评论 0原文

由于某种原因,项目“description”返回 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);
?>

这是我的数据库的架构:

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

这是页面上回显的内容:

[{"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"}]

有什么想法吗?

For some reason the item "description" returns NULL with the following code:

<?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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

情绪 2024-08-22 18:43:14

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

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

桃酥萝莉 2024-08-22 18:43:14

如果您的 PHP 版本至少为 5.5,则可以使用 json_last_error_msg()< /a>,这将返回描述问题的字符串。

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

它将返回一个整数,您可以使用该整数来识别 函数中的问题文档。目前(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

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

如果你低于5.3,那你就不走运了,没有办法询问错误是什么。

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

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.

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:

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.

无声静候 2024-08-22 18:43:14

ntd 的 anwser 没有解决我的问题。对于同样情况的人,这是我最终处理此错误的方法:
只需对每个结果进行 utf8 编码即可。

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

希望有帮助!

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.

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

Hope it helps!

晌融 2024-08-22 18:43:14

您应该在 json_encode 中传递 utf8 编码的字符串。您可以使用 utf8_encodearray_map() 函数,如下所示:

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

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

<?php
    $encoded_rows = array_map('utf8_encode', $rows);
    echo json_encode($encoded_rows);
?>
女中豪杰 2024-08-22 18:43:14

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

首先尝试:

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

如果最后一行返回 5,则问题出在您的数据上。我知道,您的表格采用 UTF-8 格式,但未输入数据。例如,输入位于 txt 文件中,但在 Win 计算机上使用愚蠢的编码创建(在我的例子中为 Win-1250 = CP1250),并且该数据已输入到数据库中。

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

您也可以仅将编码更改为 utf-8,然后手动更改所有行(使用特殊字符指定 cols - desc,...)。对奴隶有好处...

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

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.

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

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

≈。彩虹 2024-08-22 18:43:14

对于任何使用 PDO 的人来说,解决方案类似于 ntd 的答案

来自 PHP PDO::__construct 页面,作为用户的评论 < em>Kiipa 在 live.com:

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

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

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

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

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

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

装迷糊 2024-08-22 18:43:14

啊啊啊!!!这看起来太不对劲了,让我头疼。尝试更多类似这样的事情...

<?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);
?>
  • 当迭代 mysql_num_rows 时,您应该使用 < 而不是 <=。您还应该缓存该值(将其保存到变量中),而不是让它在每个循环中重新计数。谁知道它在幕后做什么......(可能很有效,我不太确定)
  • 你不需要像这样明确地复制每个值......你只是让自己变得更难。如果查询返回的值多于您在此处列出的值,请仅列出您在 SQL 中需要的值。
  • mysql_fetch_array 通过 keyint 返回值。您不使用索引,所以不要获取它们。

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

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

Perhpas 之类的东西,其中有一些特殊的字符将事情搞砸了......

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_rows you 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_array returns the values both by key and by int. You not using the indices, so don't fetch em.

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

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

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

萌面超妹 2024-08-22 18:43:14

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

mysqli_set_charset('utf8' )

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

mysqli_set_charset('utf8')

固执像三岁 2024-08-22 18:43:14

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

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 JsonSerializable on entities.

-柠檬树下少年和吉他 2024-08-22 18:43:14

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

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

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

echo '["' . implode('","', $row) . '"]';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文