Reputation: 49
I'm trying to extract the data from (php)cURL response that I received from the external api. I received the response like below.
{"result":"OK","data":{"body":{"header":"New York, New York, United States of America","query":{"destination":{"id":"1506246","value":"New York, New York, United States of America","resolvedLocation":"CITY:1506246:UNKNOWN:UNKNOWN"}},"searchResults":{"totalCount":3661,"results":[{"id":260158,"name":"Red Carpet Inn Newark/Irvington, NJ","starRating":2.0,"urls":{},"address":{"streetAddress":"100 Union Avenue","extendedAddress":"",..........
Since I'd like to extract "Red Carpet Inn Newark/Irvington" from above, I changed the php curl like below, but it will not show anything now. How should I've changed it? Could anyone suggest me what is wrong with it?
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://xxxxxxx.rapidapi.com/locations/v2/auto-complete?query=New%20York&lang=en_US&units=km",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"x-rapidapi-host: xxxxxxxx.rapidapi.com",
"x-rapidapi-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
],
]);
$response = curl_exec($curl);
// echo $response; This is origial and will show values like above.
$json = json_decode($response, TRUE);
// These are list of what I tried.
1.echo $json["name"];
2.echo $json["searchResults"]["results"]["name"];
3.
foreach ($json['results'] as $index => $v) {
echo $v['name'].'<br>';
}
Upvotes: 0
Views: 542
Reputation: 7
just remove true from json_decode() and then
$array = json_decode($json);
echo $array['whatever'];
It will work.
Upvotes: 0
Reputation: 537
You can use json_decode
to create an array and access the individual key.
$array = json_decode($json, TRUE);
echo $array['whatever'];
P.S. I'm not much into PHP, but here to help.
Upvotes: 1