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

}

Recommended Answers

All 6 Replies

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)  {...
}

"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.

"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?

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.

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.

Thanks for the update. It's indeed weird that a try catch doesn't work as expected in this situation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.