Extracting specific value from JSON string with PHP

Go To StackoverFlow.com


So I have what appears to be a pretty simple problem, though for the life of me with my lack of coding knowledge I can't figure it out. Excuse any misnomers! So I have a URL heading to a page which contains a signed request with a JSON string in it (it's a Facebook page). I need to retrieve that JSON string and then extract out just a specific part of it. I have no control over the formatting of the URL at the moment.

On the page that it goes to I have the following code:

$signed_request = $_REQUEST['signed_request']; // Get the POST signed_request variable.

if(isset($signed_request)) // Determine if signed_request is blank.
 $pre = explode('.',$signed_request); // Get the part of the signed_request we need.
 $json = base64_decode($pre['1']); // Base64 Decode signed_request making it JSON.
 $obj = json_decode($json,true); // Split the JSON into arrays.

 echo $obj['app_data'];
die('No signed request avaliable.'); //If there is no signed_request, stop processing script.

That works fine, and echo $obj['app_data']; prints: {q:"id_src=abc123456789",}

To me, that in itself is a JSON string, so I thought I could run a json_decode on that and then print out id_src=abc123456789. I tried that like this:

$appdata = $obj['app_data'];
$idcode = json_decode($appdata,true);

Followed by echo $idcode['q'], but that just prints a single curly bracket. I tried various variations, removal of ' ' marks, removal of true, etc.

My end goal is to just extract the abc123456789 value, not the id_src part. I figured it was probably faster to just ask since I'm unlikely to figure it out in the next few days.

Thanks for the help all!

EDIT: Snippet of $json added. echo $json; prints the following


Would it be the comma after the id_src value that is causing problems?

2012-04-04 00:42
by Dave
Can you post a snippet of the returned JSON after you base64_decode() it? It's possible your JSON has become corrupted somewhere in the process of fetching it, but we can't know for sure without a snippet of it - Bojangles 2012-04-04 00:46
Edited, snippet adde - Dave 2012-04-04 00:56


You can extract what you want like this:

preg_match('/"\\w+?=(\\w+?)"/', $obj['app_data'], $matches);

print_r($matches); // Array ( [0] => "id_src=abc123456789" [1] => abc123456789 )
2012-04-04 00:56
by Igor Escobar
My hero! Thanks, print_r($matches[1]) prints exactly what I want - Dave 2012-04-04 01:02
Thumbs up the answer if it helped you : - Igor Escobar 2012-04-04 01:13


{q:"id_src=abc123456789",} is not valid JSON. Try {"q":"id_src=abc123456789"}

2012-04-04 00:46
by AlienWebguy
Hmmm that's what the jsondecode function prints out, and that comes from the decoding of the signedrequest passed into the iFrame. So this could mean there is an error in the way appdata is appended to the URL - is there any way to extract the idsrc value as is - Dave 2012-04-04 00:53