json_decode(json_encode(一个索引数组))给出NULL [英] json_decode(json_encode(an indexed array)) gives NULL
问题描述
我使用json_encode对用户输入的测试区内容进行编码 这是它在mysql中的存储方式("aaa"之后返回到一行)
i encode the user entred testarea content with json_encode here is how it storred in mysql (there is a return to line after "aaa")
{"content":"aaa
bbb"}
现在,当我从数据库中获取内容并尝试使用json_decode对其进行解码时,我为此得到NULL,而不是预期的结果.
now when i get the the content from database and trying to decoded it using json_decode, i get NULL for this, instead of what expected.
出了什么问题? PHP中的错误?
what wrrong? a bug in PHP?
更多详细信息
$data =array('content'=>$textareaText);
$addres_insert = "INSERT INTO `rtable` (`data`) VALUES ('".json_encode($data)."');";
$rows = mysql_query($addres_insert);
然后获取内容
$query = "SELECT * FROM `rtable` WHERE id = '".$id."'";
$rows = mysql_query($query);
if ( $rows ){
$row = mysql_fetch_array($rows);
$res['data'] = json_decode($row['data']);//i tryed substr($row['data'],3) but didn't work
}
推荐答案
JavaScript和JSON不允许在字符串中包含换行符.您需要逃脱它们.
JavaScript and JSON do not allow line returns to be contained within a string. You need to escape them.
json_encode()
应该为您自动转义.
这是我在PHP交互式shell上使用您的JSON代码进行播放的结果:
Here is the output of my playing with your JSON code supplied on the PHP interactive shell:
php > $json = '{"content":"aaa
php ' bbb"}';
php > var_dump(json_decode($json, true));
NULL
如您所见,当我退出行时,它可以正常工作:
As you can see when I escape your line return it works just fine:
php > $json = '{"content":"aaa\n bbb"}';
php > var_dump(json_decode($json, true));
array(1) {
["content"]=>
string(8) "aaa
bbb"
}
This is also further discussed in a previous question relating to a similar problem: Problem when retrieving text in JSON format containing line breaks with jQuery
这篇关于json_decode(json_encode(一个索引数组))给出NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!