Disclaimer: I am fairly new to using json.
I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?
Here are a couple examples that I have tried based on google and stackoverflow searches.
$json_request = @file_get_contents('php://input');
$array = json_decode($json_request);
AND ALSO
$array = json_decode($_POST['data'], true);
Any suggestions?
You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
It also would not be a bad idea before you start working with the array to test that the call to
json_decode()was successful by ensuring that$arrayisn’tnullbefore use.If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example
$_POST['data']indicates that what ever called the PHP script did so passing the JSON string using thepostmethod in a variable identified asdata.You could check more generically to allow flexibility in the sending method by using the
$_REQUESTvariable, or if you know it is coming as via thegetmethod you can check$_GET.$_REQUESTholds all incoming parameters from bothgetandpost.If you don’t know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in
$_REQUESTtrying to decode each one and use the one that successfully decoded (if any). [Note: I’m not encouraging this]