带有OOP的libxml错误处理程序

Zig*_*Zag 3 php oop error-handling libxml2

我需要捕获libxml错误.但我想用我的课来做这件事.我知道libxml_get_errors和其他功能.但我需要类似的东西libxml_set_erroc_class("myclass"),在所有情况下,错误都会调用我的课程.我不希望在每种情况下使用后都$dom->load(...)创建一些类似的构造foreach(libxml_get_errors as $error) {....}.你能帮助我吗?

Bab*_*aba 8

libxml errors主要是在读取或写入xml文档时生成,因为自动验证已完成.

所以这是你应该集中注意力而你不需要覆盖的地方set_error_handler.这是概念的证明

使用内部错误

libxml_use_internal_errors ( true );
Run Code Online (Sandbox Code Playgroud)

示例XML

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

echo "<pre>" ;
Run Code Online (Sandbox Code Playgroud)

我想这是你想要达到的那种例子

try {
    $loader = new XmlLoader ( $xmlstr );
} catch ( XmlException $e ) {
    echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)

XMLLoader类

class XmlLoader {
    private $xml;
    private $doc;
    function __construct($xmlstr) {
        $doc = simplexml_load_string ( $xmlstr );

        if (! $doc) {
            throw new XmlException ( libxml_get_errors () );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

XmlException类

class XmlException extends Exception {

    private $errorMessage = "";
    function __construct(Array $errors) {

        $x = 0;
        foreach ( $errors as $error ) {
            if ($error instanceof LibXMLError) {
                $this->parseError ( $error );
                $x ++;
            }
        }
        if ($x > 0) {
            parent::__construct ( $this->errorMessage );
        } else {
            parent::__construct ( "Unknown Error XmlException" );
        }
    }

    function parseError(LibXMLError $error) {
        switch ($error->level) {
            case LIBXML_ERR_WARNING :
                $this->errorMessage .= "Warning $error->code: ";
                break;
            case LIBXML_ERR_ERROR :
                $this->errorMessage .= "Error $error->code: ";
                break;
            case LIBXML_ERR_FATAL :
                $this->errorMessage .= "Fatal Error $error->code: ";
                break;
        }

        $this->errorMessage .= trim ( $error->message ) . "\n  Line: $error->line" . "\n  Column: $error->column";

        if ($error->file) {
            $this->errorMessage .= "\n  File: $error->file";
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

样本输出

Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

谢谢