2014-10-15 11 views
5

Sto provando a caricare xml che ha tag non corrispondenti e mi aspettavo che qualcosa del genere funzionasse ma senza fortuna.Come ottenere errori di analisi con DomDocument :: loadXML()

try{ 
    $xml=new \DOMDocument('1.0','utf-8'); 
    $xml->loadXML(file_get_contents($file), 
}catch (\Exception $e){ 
    echo $e->getMessage());   
} 

Ora ho davvero bisogno di generare un'eccezione per gli errori di analisi. Ho provato a passare options per caricareXML

LIBXML_ERR_ERROR|LIBXML_ERR_FATAL|LIBXML_ERR_WARNING 

di nuovo senza fortuna. Per favore guidami come catturare tutti questi errori di analisi.

Modifica

Come suggerito da @Ghost nei commenti, mi è venuto in giro questa soluzione

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(); 
     } 
    } 

.... 
} 

Così il trucco è quello di chiamare libxml_use_internal_errors(true); e quindi controllare loadXML() Stato esempio

if(!$xml->loadXML(file_get_contents($file))){ 
    $this->handleXmlException(); 
} 

Non so se questo libxml_use_internal_errors(true); abbia qualche effetto collaterale finora

+0

forse legati http://stackoverflow.com/questions/10025247/libxml-error-handler-with-oop – Ghost

+0

grazie @Ghost :) – sakhunzai

+0

uomo che nessuno prob – Ghost

risposta

2

È possibile attivare libxml_use_internal_errors e ottenere gli errori con 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); 
    } 
Problemi correlati