Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parse errors with DOMDocument::loadXML()

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.

Edit

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

like image 962
sakhunzai Avatar asked Oct 15 '14 06:10

sakhunzai


1 Answers

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);
  }
like image 78
Demodave Avatar answered Sep 22 '22 17:09

Demodave