Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial php使用json_decode解析json返回NULL

php使用json_decode解析json返回NULL

Jun 20, 2016 pm 12:33 PM

问一下各位高手,为啥json_decode解析$_POST['mypostdata']字符串会是null,但是把$_POST['mypostdata']复制到php文件中可以正常解析,怎么办?请大家指点一下!代码如下:
header('content-type:text/html; charset=utf-8');
$member_info=$_POST['mypostdata'].trim();
$encode = mb_detect_encoding($member_info, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
echo $member_info.'
';
echo $encode.'
';
$arr = json_decode($member_info,true);
if ($arr == null) echo 'arr是null
';
?>
打印输出:

[["90987682","陈好茹","管理"],["309888729","张先生","管理"],["56439871","jack","管理"],["76398723","李洁","e"]]
UTF-8
arr是null

当然问这个问题之前,楼主也是在网上查了很久的资料例如 (php使用json_decode返回NULL):http://www.nginx.cn/337.html 提到的3种解决办法:
1. json字符串必须以双引号包含
$output = str_replace("'", '"', $output);
2. json字符串必须是utf8编码
$output = iconv('gbk', 'utf8', $output);
3.不能有多余的逗号 如:[1,2,]
用正则替换掉,preg_replace('/,\s*([\]}])/m', '$1', $output)
对于1,2,3对比打印的字符串格式应该是没有问题的,上面的编码也打印出来了是UTF-8的,还真的不知道是咋回事!

另外楼主用的php版本PHP Version 5.2.6应该是用不了json_last_error()函数的 参考:http://php.net/manual/zh/function.json-last-error.php
json_last_error — 返回最后发生的错误  (PHP 5 >= 5.3.0, PHP 7)

-------------------分割线:楼主直接接上面红色部分的json字符串复制到$member_info做json解析,而不是通过post参数获取----------------------
$member_info='[["90987682","陈好茹","管理"],["309888729","张先生","管理"],["56439871","jack","管理"],["76398723","李洁","e"]]';
$encode = mb_detect_encoding($member_info, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
echo $member_info.'
';
echo $encode.'
';
$arr = json_decode($member_info,true);
if ($arr == null) {
 echo 'arr是null
';
} else {
  foreach($arr as $ele_arr) {
       echo '名字:'.$ele_arr[1];
       echo '
';
  }
}
?>
打印输出

[["90987682","陈好茹","管理"],["309888729","张先生","管理"],["56439871","jack","管理"],["76398723","李洁","e"]]
UTF-8
名字:陈好茹
名字:张先生
名字:jack
名字:李洁

再不确定的问一下:以上应该说明json格式是没有问题的? 字符utf-8编码也是没有问题的?


回复讨论(解决方案)

看上去没有问题
你 echo base64_encode($_POST['mypostdata']); 贴出结果,让我分析一下

看上去没有问题
你 echo base64_encode($_POST['mypostdata']); 贴出结果,让我分析一下


一下是base64_encode数据,多谢了!

W1tcIjkwOTg3NjgyXCIsXCLpmYjlpb3ojLlcIixcIueuoeeQhlwiXSxbXCIzMDk4ODg3MjlcIixcIuW8oOWFiOeUn1wiLFwi566h55CGXCJdLFtcIjU2NDM5ODcxXCIsXCJqYWNrXCIsXCLnrqHnkIZcIl0sW1wiNzYzOTg3MjNcIixcIuadjua0gVwiLFwiZVwiXV0

$s = base64_decode("W1tcIjkwOTg3NjgyXCIsXCLpmYjlpb3ojLlcIixcIueuoeeQhlwiXSxbXCIzMDk4ODg3MjlcIixcIuW8oOWFiOeUn1wiLFwi566h55CGXCJdLFtcIjU2NDM5ODcxXCIsXCJqYWNrXCIsXCLnrqHnkIZcIl0sW1wiNzYzOTg3MjNcIixcIuadjua0gVwiLFwiZVwiXV0");echo $s;
Copy after login
[[\"90987682\",\"陈好茹\",\"管理\"],[\"309888729\",\"张先生\",\"管理\"],[\"56439871\",\"jack\",\"管理\"],[\"76398723\",\"李洁\",\"e\"]]
Copy after login

可以看到双引号被转义了,显然你的 magic_quotes_gpc 开关是打开的(到 php5.4 这个开关就无效了)
由于使用了自动转义,所以不是直接入库的话,需要去转义
if(get_magic_quotes_gpc()) {	if(isset($_GET)) $_GET = unTurn($_GET);	if(isset($_POST)) $_POST = unTurn($_POST);}//去转义function unTurn($val) {	if(is_array($val)) {		$val = array_map('unTurn', $val);	}else {		$val = stripslashes($val);	}	return $val;}
Copy after login


$s = base64_decode("W1tcIjkwOTg3NjgyXCIsXCLpmYjlpb3ojLlcIixcIueuoeeQhlwiXSxbXCIzMDk4ODg3MjlcIixcIuW8oOWFiOeUn1wiLFwi566h55CGXCJdLFtcIjU2NDM5ODcxXCIsXCJqYWNrXCIsXCLnrqHnkIZcIl0sW1wiNzYzOTg3MjNcIixcIuadjua0gVwiLFwiZVwiXV0");$s = stripcslashes($s);print_r(json_decode($s, true));
Copy after login
Array(    [0] => Array        (            [0] => 90987682            [1] => 陈好茹            [2] => 管理        )    [1] => Array        (            [0] => 309888729            [1] => 张先生            [2] => 管理        )    [2] => Array        (            [0] => 56439871            [1] => jack            [2] => 管理        )    [3] => Array        (            [0] => 76398723            [1] => 李洁            [2] => e        ))
Copy after login

好吧,果然版主,思路清晰,问题解决直接了当,毫不拖泥带水,多谢了。 本来可以结贴了,不过本着能慧更多人的目的,请版主分享一下解决这类问题的心得呗!


学习了。

很好用,好理解

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles