I am trying to load xml which has mismatched tags and I expected something like this to work but without 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 parse errors. I tried to pass options to loadXML
LIBXML_ERR_ERROR|LIBXML_ERR_FATAL|LIBXML_ERR_WARNING
again no luck. Please guide me how to catch all these parse errors.
As suggested by @Ghost in comments, I came around 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 loadXML() status e.g
if(!$xml->loadXML(file_get_contents($file))){
$this->handleXmlException();
}
I don't know if this libxml_use_internal_errors(true);
has any side-effect so far
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With