Reputation: 314
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);
}
Upvotes: 1
Views: 3512
Reputation: 1375
use json_encode()
to encode the data , then print the json
$data = json_decode(file_get_contents("php://input"));
echo json_encode($data);
Upvotes: 0
Reputation: 781058
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;
Upvotes: 4
Reputation: 1172
curl_close($curl);
$result = json_decode($jsonResponse, true);
echo $result['item1']; //Echo item 1.
Upvotes: -1
Reputation: 266
You don't need set second param in json_decode function for getting stdClass.
$data = array(
'item1' => 'value1',
'item2' => 'value2',
'item3' => 'value3'
);
$json=json_encode($data);
$result=json_decode($json);
echo $result->item1;
echo $result->item2;
echo $result->item3;
Or you can work with array
$json=json_encode($data);
$result=json_decode($json, true);
echo $result['item1'];
echo $result['item2'];
echo $result['item3'];
Upvotes: 0