This is a simple JSON but it cannot access an item. I send the that JSON to get.php and there just print_r the JSON and in parsing JSON response is problem.
My code:
$url = "http://localhost/get.php";
$data = array(
'item1' => 'value1',
'item2' => 'value2',
'item3' => 'value3'
);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status == 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, false);
$result=json_encode($json_response);
$data=json_decode($result);
How can I echo item 1 or 2 ?
This is get.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
print_r($data);
}
echo $result['item1'];,echo $result['item2'];will do. BTW there's no point encoding it, and then decoding it again.stdClass Object? When you usetrueas the second argument tojson_decode()it returns an associative array, not an object.