PHPでXML形式のデータを扱うにはlibxmlライブライを使うことが一般的です。
libxml内でのエラー発生時の処理は、libxml_use_internal_errorsの設定で、下記の2通りの設定が可能です。
- libxml_use_internal_errors(false): Exceptionとして投げる。
- libxml_use_internal_errors(true): libxml_get_errors()で取得。※libxml_clear_errorsで事前にエラーをクリアしておく方が無難。
libxml_use_internal_errors(true)に設定して、Exceptionを発生させないようにする関数のサンプルを示します。
$excecutionに実際のXML処理を渡します。
function executeInLibXmlUseInternalErrors(callable $execution)
{
// 現在のlibxml_use_internal_errorsの設定を処理後に戻すために保存
$useErrors = libxml_use_internal_errors();
try {
libxml_clear_errors();
libxml_use_internal_errors(true);
return $execution();
} finally{
// 処理が終わったらlibxml_use_internal_errorsの設定をもとに戻す
libxml_use_internal_errors($useErrors);
}
}
// 下記はXPathでDOMDodumentからXMLの要素を取得する場合の使用例です。
// XMLの処理中にもExceptionが発生しないので、プログラム内で処理することができます。
$xpath = '/xpath';
$file = '/path_to_xml_file';
$result = executeInLibXmlUseInternalErrors(function() use($file, $xpath){
$doc = new \DOMDocument();
if (!$doc->load($file)) {
foreach (libxml_get_errors() as $error) {
// handle errors here
}
}
$domXpath = new \DOMXPath($doc);
$result = $domXpath->query($xpath);
if (!$result) {
foreach (libxml_get_errors() as $error) {
// handle errors here
}
}
libxml_clear_errors();
return $result;
});
コメント