PHPのXMLReaderの内部で発生したエラーは、Exceptionではないためtry~catchブロックで捕まえることができません。
Exceptionとして捕まえるためには、set_error_handlerを使って、自前でエラーをExceptionに変換して投げる必要があります。
下記のコードで実現できます。
<?php
// operationにエラーを発生させる可能性のある処理ブロックを渡す。
function caputureNativeErrorAndThrowIt(callable $operation)
{
$errorReportingLevel = error_reporting(E_ALL);
set_error_handler(function(
int $serverity,
string $message,
string $file,
int $line
): void{
throw new \ErrorException($message, 0, $serverity, $file, $line);
});
try
{
$operation();
} finally {
restore_error_handler();
error_reporting($errorReportingLevel);
}
}
// 下記はcaputureNativeErrorAndThrowIt関数をXMLReaderで使用した場合の例です。
$path = 'path_to_invalid_xml_file';
$reader = new \XMLReader();
$reader->open($path);
caputureNativeErrorAndThrowIt(function() use($reader){
try {
while($reader->read()){
// do something
}
} finally{
$reader->close();
}
});
コメント