Skip to content

Instantly share code, notes, and snippets.

@dcb9
Last active August 29, 2015 14:25
Show Gist options
  • Save dcb9/83afee8dad45acbfbf5b to your computer and use it in GitHub Desktop.
Save dcb9/83afee8dad45acbfbf5b to your computer and use it in GitHub Desktop.
json-decode-Control-character-error
{"msg_item":[{"id":204993425,"type":9,"fakeid":"3076920206","nick_name":"敢玩","date_time":1427459682,"content":"","source":"mass","msg_status":2,"title":"敢玩初体验 | 告别不靠谱的副机长!普通人也能开飞机!","desc":"听到前两的德法坠机事件你对飞行产生恐惧?告别那些不靠谱的副机长吧,自己也可以亲身做一回副机长。看了视频你就","content_url":"http:\/\/mp.weixin.qq.com\/s?__biz=MzA3NjkyMDIwNg==&mid=204993424&idx=1&sn=3d49b4e5d8c688a1858c7fdb6bd65f88#rd","show_type":1,"file_id":204978640,"app_sub_type":3,"comment_url":"","has_reply":0,"refuse_reason":"","multi_item":[{"seq":0,"cover":"https:\/\/mmbiz.qlogo.cn\/mmbiz\/Nbw8zgku2MiaIF7hSpax7Vb75Ze2gZfJt2uDQ1v72Ds9RhlYT0hEE1L4YUJdA1zVwUqzBqI0ks8Dw0RIw8P53GA\/0","title":"敢玩初体验 | 告别不靠谱的副机长!普通人也能开飞机!","digest":"听到前两的德法坠机事件你对飞行产生恐惧?告别那些不靠谱的副机长吧,自己也可以亲身做一回副机长。看了视频你就","content_url":"http:\/\/mp.weixin.qq.com\/s?__biz=MzA3NjkyMDIwNg==&mid=204993424&idx=1&sn=3d49b4e5d8c688a1858c7fdb6bd65f88#rd","file_id":204978640,"content":"","source_url":"","author":"I Love","show_cover_pic":0,"del_flag":0,"vote_id":[],"copyright_status":100,"copyright_type":0,"super_vote_id":[],"is_deleted":0,"msg_id":204993424},{"seq":1,"cover":"https:\/\/mmbiz.qlogo.cn\/mmbiz\/Nbw8zgku2MiaIF7hSpax7Vb75Ze2gZfJt2fF2BTpvv5H7Y8JbdURlAJIaxxPtcVDV7OlKupEWVaPNqCTefqNmhA\/0","title":"敢玩活动【北京】 | 燃烧冰滑板大乱斗,免费奖品等你拿!","digest":"3月28号相关比赛环节的预告已经放出,BEST LINE路线演示,和好玩的趣味游戏:滑板沙狐球,就等你来挑战","content_url":"http:\/\/mp.weixin.qq.com\/s?__biz=MzA3NjkyMDIwNg==&mid=204993424&idx=2&sn=702f9535784c8bfbc6d33c1a6886f4ab#rd","file_id":204962582,"content":"","source_url":"","author":"","show_cover_pic":0,"del_flag":0,"vote_id":[],"copyright_status":100,"copyright_type":0,"super_vote_id":[],"is_deleted":0,"msg_id":204993424}],"to_uin":0,"send_stat":{"total":0,"succ":0,"fail":0,"progress":0},"copyright_status":100,"copyright_type":0,"is_send_all":1}]}
<?php
$content = file_get_contents('a.json');
$content = preg_replace('/\x1D/', '', $content);
$json = json_decode($content, true);
var_dump($json); // Output: json data
echo json_last_error_msg(); // Output: No error
<?php
$content = file_get_contents('a.json');
$json = json_decode($content, true);
var_dump($json); // Output: null
echo json_last_error_msg(); // Output: Control character error, possibly incorrectly encoded
@dcb9
Copy link
Author

dcb9 commented Jul 24, 2015

解决步骤

  • 通过 vim 打开 a.json 看一下,可以看到 ^] 这样一个控制符
  • 查看 ^] 控制符所对应的十六进制 控制字符列表
  • 使用 preg_replace('/\x1D/', '', $str) 把控制符给删除
  • 在第 3 行下面插入一行替换代码,即可成功运行。$content = preg_replace('/\x1D/', '', $content);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment