2

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?

3
  • Do a var_dump on $obj. Commented Apr 14, 2013 at 0:27
  • 1
    Your query string is wrong.. there is no data=. Commented Apr 14, 2013 at 0:29
  • You're right. What should this be instead? Commented Apr 14, 2013 at 0:33

2 Answers 2

5

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh, you're right! But even with data set in the URL, why doesn't this work? $data = $_GET['data']; $obj = json_decode($data);
Thanks for the help guys. Turned out I needed stripslashes($data), then it worked!
1

you should do

echo $obj->{'Name'};

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

3 Comments

What is the difference to call it without {} ??
$obj->Name and $obj->{'Name'} are equivalent in this case; this answer is useless.
@hek2mgl there is none (in this case) :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.