I know there are a lot of different posts asking about the same problem, and I have already tried all of them and still couldn't find a solution. so please feel free to refer me to right answer if there is one.
I am getting a JSON post request from an Ionic 2 application to my PHP server. The attached JSON includes some data from SQLite which I need to insert into my MySQL database using PHP script.
This is how I am accessing the JSON and Processing.
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content,True);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
For test, I am printing my JSON into a file by running the code below
$file = 'log.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Write the contents back to the file
file_put_contents($file, $decoded);
Here is Response I get in log.txt file which is a valid JSON
[
{
"Date":"October 13th 2017, 6:21:32",
"ID":"20000",
"Age":1
},
{
"Date":"October 11th 2017, 7:21:32",
"ID":"20001",
"Age":1
}
]
Problem:
How can I assign ID value from the above JSON to a new variable?
Already tried with no sucdess:
$decoded = json_decode($content);
foreach ($decoded as $obj) {
file_put_contents($file, $obj->ID);
}
$decodedarray = json_decode($content,True);
foreach ($decodedarray as $arr) {
file_put_contents($file, $arr['ID']);
}