"Trying to get property of non-object" error with SimpleXML and PHP
- by SooDesuNe
I'm using a PHP script with SimpleXML to parse an XML feed. I have no control over the content of the XML.
try { $xml = @new SimpleXMLElement($fetchResult); } catch (Exception $e) { errorHandle($e->getMessage());}
$userNick = $xml->View->ScrollView->VBoxView->View->MatrixView->VBoxView[0]->HBoxView->TextView->SetFontStyle->b;
foreach ($xml->View->ScrollView->VBoxView->View->MatrixView->VBoxView[0]->VBoxView as $pathToSubTree){
foreach ($pathToSubTree->MatrixView->View->VBoxView->VBoxView->HBoxView[0]->VBoxView->MatrixView->VBoxView as $canopy){
//Do some stuff now that we've found the canopy of the tree
}
$canopy = $pathToSubTree->MatrixView->View->VBoxView->VBoxView->HBoxView[0]->VBoxView->MatrixView->VBoxView;
if(is_null($canopy)){
//Do some stuff stuff is the canopy was not traceable
}
}
$pathToSubTree = $xml->View->ScrollView->VBoxView->View->MatrixView->VBoxView[0]->VBoxView;
if(is_null($pathToSubTree)){
//Do some stuff stuff is the subTree path was not traceable
}
unset($xml);
I'm getting lots of two errors, which I'm sure are related to the same cause:
PHP Notice: Trying to get property of non-object in myScript.php on line 45
PHP Warning: Invalid argument supplied for foreach() in myScript.php on line 45
PHP Notice: Trying to get property of non-object in myScript.php on line 76
Line 45 is (from above):
foreach ($pathToSubTree->MatrixView->View->VBoxView->VBoxView->HBoxView[0]->VBoxView->MatrixView->VBoxView as $canopy){
Line 76 is (from above):
$canopy = $pathToSubTree->MatrixView->View->VBoxView->VBoxView->HBoxView[0]->VBoxView->MatrixView->VBoxView;
I'm pretty sure this error is caused by one of the arrays in my path not being an array for the particular XML, but some times it CAN be an array.
What's the correct way to deal with these?