Reputation: 9
Following errors show up for the code given below:
Undefined property: stdClass::$duration in C:\wamp\www\temp\yy.php
trying to get property of non-object in C:\wamp\www\temp\yy.php
How to resolve?
$q = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$a,$b&destinations=$c,$d&mode=driving&sensor=false";
$json = file_get_contents($q);
$details = json_decode($json);
$d=$details->rows[0]->elements[0]->duration->text;
Upvotes: 0
Views: 122
Reputation: 146201
You may try something like this:
if($details->rows[0]->elements[0]->status == 'OK') {
$text = $details->rows[0]->elements[0]->duration->text;
}
If no results were returned then you may get following as $details->rows[0]->elements[0]
:
stdClass Object
(
[status] => ZERO_RESULTS
)
If a result were returned then you will get something like this as $details->rows[0]->elements[0]
:
stdClass Object
(
[distance] => stdClass Object
(
[text] => 1Â 716 km
[value] => 1715523
)
[duration] => stdClass Object
(
[text] => 3 jours 19 heures
[value] => 329133
)
[status] => OK
)
So, if $details->rows[0]->elements[0]->status
is OK
then there is a distance
and a duration
property and each one contains an stdClass
object with two properties as text
and value
. Make sure you are passing right data within your variables ($a
, $b
, $c
and $d
).
Try this for example:
Upvotes: 1
Reputation: 2171
The error message you're receiving is telling you exactly what the problem is. The duration
property is not found on the object returned by json_decode
; the above query you are making in the referenced code block (i.e. this one) returns the following JSON:
{
"destination_addresses" : [ "Catamarca Province, Argentina" ],
"origin_addresses" : [ "Augsburg, Germany" ],
"rows" : [
{
"elements" : [
{
"status" : "ZERO_RESULTS"
}
]
}
],
"status" : "OK"
}
Looking at this, there is no duration
element returned in the above, therefore the following call:
$json = file_get_contents($q);
$details = json_decode($json);
$d=$details->rows[0]->elements[0]->duration->text;
Will result in the error you're seeing.
You can use error handling (e.g. try...catch
) to get the duration and the text if it exists, or test to see if the property exists, etc.
Basically, what it boils down to is that without additional code, you can't rely on the fact that duration
will be an element of that returned JSON
and you have to account for it.
Upvotes: 0