There is an API that result is for example like this:
// 20190920173100
//api.opencagedata.com/geoc
{
"documentation": "https://opencagedata.com/api",
"licenses": [
{
"name": "see attribution guide",
"url": "https://opencagedata.com/credits"
}
],
"rate": {
"limit": 2500,
"remaining": 2493,
"reset": 1569024000
},
"results": [
{
"bounds": {
"northeast": {
"lat": 51.9528202,
"lng": 7.6325938
},
"southwest": {
"lat": 51.9525445,
"lng": 7.6323594
}
},
"components": {
"ISO_3166-1_alpha-2": "DE",
"ISO_3166-1_alpha-3": "DEU",
"_type": "building",
"city": "Münster",
"city_district": "Münster-Mitte",
"continent": "Europe",
"country": "Germany",
"country_code": "de",
"county": "Münster",
"house_number": "7",
"neighbourhood": "Josef",
"political_union": "European Union",
"postcode": "48153",
"road": "Friedrich-Ebert-Straße",
"state": "North Rhine-Westphalia",
"state_district": "Regierungsbezirk Münster",
"suburb": "Innenstadtring"
},
"confidence": 10,
"formatted": "Friedrich-Ebert-Straße 7, 48153 Münster, Germany",
"geometry": {
"lat": 51.9526599,
"lng": 7.632473
}
}
],
"status": {
"code": 200,
"message": "OK"
},
"stay_informed": {
"blog": "https://blog.opencagedata.com",
"twitter": "https://twitter.com/opencagedata"
},
"thanks": "For using an OpenCage API",
"timestamp": {
"created_http": "Fri, 20 Sep 2019 13:01:02 GMT",
"created_unix": 1568984462
},
"total_results": 1
}
I want to use the above data.
I tried the following code:
$adress = json_decode(file_get_contents("https://api...."));
$detail = $adress ->rate->limit;
and it is ok
The problem is when I use this code to get results data it is null for example
$adress = json_decode(file_get_contents("https://api...."));
$detail = $adress ->result>formatted;
I guess that it is because of the object and array
2
Answers
$results
is an array, so you have to do :$detail = $adress ->results[0]->formatted;
Don’t use file_get_contents function (This function reads entire file into a string)
Because a URL can be used as a filename with this function if the fopen wrappers have been enabled only as described here. That is because sometimes this is closed (depending on your host, like shared hosting) and because of that, your application will not work.
So my best suggestion is to use curl() (Client URL)
So according to your case you are requesting data from the API. So, we can use the
GET
method to request data with curl() as follows with some headers,So now the response comes back in a JSON object. Now you can use json_decode() to put this into a usable object or array as you already did this.
As will already answered in his answer, unlike
rate
, theresults
object is an array containing your data. So you have to change yourresult
toresults[0]
in order to read theformatted
data.