I am trying to download an xml that has inappropriate tags, and I expected something like this to work, but with no luck.
try{ $xml=new \DOMDocument('1.0','utf-8'); $xml->loadXML(file_get_contents($file), }catch (\Exception $e){ echo $e->getMessage()); }
Now I really need to throw an exception for parsing errors. I tried passing parameters for loading xml
LIBXML_ERR_ERROR|LIBXML_ERR_FATAL|LIBXML_ERR_WARNING
again no luck. Please tell me how to catch all these parsing errors.
Edit
As suggested by @Ghost in the comments, I found this solution
abstract class XmlReadStrategy extends AbstractReadStrategy { protected $importAttributes; public function __construct($fileFullPath,$fileName) { parent::__construct($fileFullPath,$fileName); libxml_use_internal_errors(true); } protected function handleXmlException(){ $this->dataSrc=array(); foreach(libxml_get_errors() as $e){ $this->logger->append(Logger::ERROR,'[Error] '.$e->message); } } protected function loadImportFileData($file) { try{ $xml=new \DOMDocument('1.0','utf-8'); if(!$xml->loadXML(file_get_contents($file))){ $this->handleXmlException(); } $this->dataSrc=$this->nodeFilter($xml); }catch (\Exception $e){ $this->logger->append(Logger::ERROR,$e->getMessage()); $this->dataSrc=array(); } } .... }
So, the trick is to call libxml_use_internal_errors(true); and then check the status of loadXML (), for example,
if(!$xml->loadXML(file_get_contents($file))){ $this->handleXmlException(); }
I do not know if this libxml_use_internal_errors(true); any side effect
source share