0

I'm using simplexml_load_string to extract a node from an xml filen xml file. It works most of the time, but not all, and when it fails, it gives the error:
"call to a member function xpath() on a non-object"

I suspect it's because the $menuXML isn't fully loaded? It is dynamic, so may change. The code should handle this and simply ignore it until the next time it is analysed.

I did try using libxml_use_internal_errors to try and prevent the exceptions affecting the code, but it didn't work. I could use try/catch, but is there a better way?

snip of code:

$xml = simplexml_load_string($menuXML, null, null, "http://www.w3.org/2001/XMLSchema-instance/");
if ($xml !==FALSE) {
$dump = $xml->xpath('books'); //fails here

}
2
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by pritaeas
0

Update.
I changed the code to use a try catch, but it's still failing on the same line, with the
"call to a member function xpath() on a non-object " on the file at the line identified in the code snippet.

I can't seem to get the code to handle the exception more gracefully without crashing out.

snip of code:

$xml = simplexml_load_string($menuXML, null, null, "http://www.w3.org/2001/XMLSchema-instance/");
if ($xml) {
try {
$dump = $xml->xpath('books'); //**reports fail here**
}
catch (Exception $e)  {...
}
0

"call to a member function xpath() on a non-object " suggests that $xml is not a proper object. Therefore I think that the XML in $menuXML is malformed.

0

"call to a member function xpath() on a non-object " suggests that $xml is not a proper object. Therefore I think that the XML in $menuXML is malformed.

I expected as much, but want to know how to just ignore the exception and carry on with the next loop. At the moment the code just crashes on the xpath. I'd like to be able to carry on having maybe logged the error.

Is there a way to do this?

0

Apparently $xml is not false. Echo the value to see what it does contain. Perhaps it is null. If it is then you can add that check to the if.

0

I've tried all sorts on the xml, but checking for a wellformed xml before the functions seems to have fixed it:

$wellformed = TRUE;
$parser = xml_parser_create ();
if (xml_parse ($parser, $menuXML, true)) {
	$xml = simplexml_load_string($menuXML, null, null, "http://www.w3.org/2001/XMLSchema-instance/");
}
else {
	$wellformed = FALSE;
}
xml_parser_free ($parser);

I only allow the xpath to operate if it's wellformed.
It hasn't crashed (yet), so I'm hoping it's ok, but I'm surprised that all the exception handling can't be intercepted as I'd expect.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.