I'm currently validating XML prior to reading it using the following validation funcition I put together...
public static function validate($xml) {
libxml_use_internal_errors(TRUE);
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xml);
$errors = libxml_get_errors();
if (empty($errors)) { return TRUE; }
$error = $errors[0];
if ($error->level < 3) {
return TRUE;
} else {
return $errors;
}
}
and once it's been validated we jump into reading the XML using a while loop basically like so...
$reader = new XMLReader();
$reader->xml($xml);
while($xml->read()) { ... }
The problem I'm having is for some reason, some XML is passing validation, but is causing errors during the read()
operation. In our case, the body of the while loop is substantial so it's unrealistic to wrap it in a try/catch block if that's even possible (I don't think these are exceptions, but correct me if I'm wrong).
What is the best way to capture errors emanating from our while
loop's read()
method?
The only solution I've been able to find so far is from here: http://www.ibm.com/developerworks/library/x-pullparsingphp/ using the track_errors
PHP INI setting, but this seems like overkill for capturing errors in one spot, is there no other way?
EDIT: The error level coming from the read()
errors is E_WARNING
, and the exact error message is XMLReader::read(): An Error Occured while reading
.
EDIT 2: I've found the following SO question which relates: Getting PHP's XMLReader to not throw php errors in invalid documents however there's seems to be conflicting reports of whether the solutions work in the comments. In any case, they're all workarounds.