How do I parse a JSON object in PHP?

2019-05-27 04:21发布

I've got a JSON object that I'm sending to a PHP script and I'm having trouble parsing the JSON. Here's the POST request:

http://mywebsite.com?action=somefunction&{%22id%22:1,%22Name%22:%22Mike%22}

And here's my PHP function, which obviously doesn't work:

$data = $_GET['data'];
$obj = json_decode($data);
echo $obj->Name;
die();

The end goal is to extract the name "Mike" from the URL string. Any suggestions?

2条回答
放荡不羁爱自由
2楼-- · 2019-05-27 04:23

Try taking a look at what PHP is outputting from json_decode():

$data = $_GET['data'];
$obj = json_decode($data);
var_dump($obj);

Your code itself works fine: http://ideone.com/0jsjgT

But your query string is missing the data= before the actual JSON. This:

http://mywebsite.com?action=somefunction&{%22id%22:1,%22Name%22:%22Mike%22}

should be this:

http://mywebsite.com?action=somefunction&data={%22id%22:1,%22Name%22:%22Mike%22}
查看更多
叼着烟拽天下
3楼-- · 2019-05-27 04:47

you should do

echo $obj->{'Name'};

This also is a duplicate question of Echo data json by json_decode

查看更多
登录 后发表回答