Dynamically access nested object
When you do
$xml->{$lat_path};
PHP will use anything within $lat_path
as the variable name. It will not go into the object graph or obey the T_OBJECT_OPERATOR
at all. It will simply look for a property
'result[0]->geometry->location->lat;'
in $xml
. Try to run this code for an example:
$obj = new StdClass;
$obj->{'result[0]->geometry->location->lat;'} = 1;
print_r($obj);
It will output
stdClass Object
(
[result[0]->geometry->location->lat;] => 1
)
As you can see, it is one single property, not a nested object graph.
Like suggested in the comments, either use XPath or go to the desired value directly:
$xml->result[0]->geometry->location->lat;
If you're not able to use xPath and need to access a object dynamically, you can use the following approach:
$oObj = new StdClass;
$oObj->Root->Parent->ID = 1;
$oObj->Root->Parent->Child->ID = 2;
$sSeachInTree = 'Root\\Parent\\Child\\ID';
$aElements = explode("\\",$sSeachInTree);
foreach($aElements as $sElement)
{
if (isset($oObj->{$sElement}))
{
if (end($aElements) == $sElement)
{
echo "Found: " . $sElement . " = " . $oObj->{$sElement};
}
$oObj = $oObj->{$sElement};
}
}