当xml有解析错误时,PHP DOM LoadXML处理无限循环


PHP DOM LoadXML processing infinite loop when xml has parse errors

如何在xml数据有解析错误时停止循环?

//xml data <column><col>Col1</col><col>Col2</col><col>Col3</col><column>
$xml = new DOMDocument();
$xml->loadXML($item_xml);
//loads the data
// find column
if(!empty(   $xml->documentElement)){
   foreach(  $xml->documentElement->childNodes as $xmlChild){
          if($xmlChild->nodeName == 'column'){
             return $xmlChild;
         }
    }
}

如果任何XMl解析错误。连续处理,不抛出任何异常。

如何避免xml解析错误?

您可以使用libxml_get_errors():

$xml = new DOMDocument();
// Don't display errors and warnings
$errorState = libxml_use_internal_errors(TRUE);
// Load the XML now
$xml->loadXML($item_xml);
// Get all the errors, as an array
$errors = libxml_get_errors();
// If the array is not empty
if(!empty($errors)) {
    // Markup contains error(s)
}