Mohammadali Mirahamed Mohammadali Mirahamed - 2 months ago 8
JSON Question

How to echo JSON in PHP (stdClass Object)?

This is simple Json but i can not access to the 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 is below:

$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 ?

And this is get.php

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
print_r($data);
}

Answer

Since get.php uses print_r(), it's not returning JSON. It needs to use json_encode().

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
  $data = json_decode(file_get_contents("php://input"));
  echo json_encode($data);
}

Then your curl script can decode it properly.

$response = json_decode($json_response, false);
echo 'Item1 = ' . $response->item1 . '<br>';
echo 'Item2 = ' . $response->item2 . '<br>';
echo 'Item3 = ' . $response->item3;