Catch PHP errors if XML file is empty

so I grab some information from an XML file, for example:

$url = "http://myurl.blah"; $xml = simplexml_load_file($url); 

Unless the XML file is empty and I need the code to fail, but I cannot figure out how to catch the PHP error. I tried this:

 if(isset(simplexml_load_file($url))); { $xml = simplexml_load_file($url); /*rest of code using $xml*/ } else { echo "No info avilable."; } 

But that will not work. I think you cannot use ISSET in this way. Does anyone know how to catch a bug?

+2
source share
4 answers
 $xml = file_get_contents("http://myurl.blah"); if (trim($xml) == '') { die('No content'); } $xml = simplexml_load_string($xml); 

Or perhaps a little more efficient, but not necessarily recommended, as it keeps silent about errors:

 $xml = @simplexml_load_file($url); if (!$xml) { die('error'); } 
+9
source

Do not use isset here.

 // Shutdown errors (I know it bad) $xml = @simplexml_load_file($url); // Check you have fetch a response if (false !== $xml); { //rest of code using $xml } else { echo "No info avilable."; } 
+1
source
 if (($xml = simplexml_load_file($url)) !== false) { // Everything is OK. Use $xml object. } else { // Something has gone wrong! } 
+1
source

From the PHP manual, error handling ( click here ):

 var_dump(libxml_use_internal_errors(true)); // load the document $doc = new DOMDocument; if (!$doc->load('file.xml')) { foreach (libxml_get_errors() as $error) { // handle errors here } libxml_clear_errors(); } 
0
source

Source: https://habr.com/ru/post/1438881/


All Articles