How to get parsing errors using DomDocument :: loadXML ()

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 { /** @var array */ protected $importAttributes; /** * @param $fileFullPath * @param $fileName */ 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); } } /** * Import xml file * @param string $file * @throws \Exception */ 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

+5
source share
1 answer

You can enable libxml_use_internal_errors and get errors with libxml_get_errors ()

  libxml_use_internal_errors(true); $xml = new DOMDocument('1.0','utf-8'); if ( !$xml->loadxml(file_get_contents($file)) ) { $errors = libxml_get_errors(); var_dump($errors); } 
+2
source

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


All Articles