2012-10-17 52 views
1

可能重复:
PHP Catching a SimpleXMLElement parse error使用尝试捕捉得到警告消息在PHP

我使用的XML文件,文件上传。我用simplexml_load_file("files/sample.xml"); 如果给出的xml文件错误意味着,它会显示这样的警告,

Warning (2): simplexml_load_file() [http://php.net/function.simplexml-load-file]: files/sample.xml:8: parser error : Opening and ending tag mismatch: 
Warning (2): simplexml_load_file() [http://php.net/function.simplexml-load-file]: 

我已经开始使用尝试捕捉警告。我正在使用CakePHP

+0

这不是很明显,这取决于输入文件?展示下!除非问题不是关于警告。 – AndreKR

+0

我在这里使用,尽量{ \t \t \t \t \t \t \t $ XML =使用simplexml_load_file( “文件/ sample.xml中”); \t \t \t \t \t \t} \t \t \t \t \t \t赶上(例外$ E){ \t \t \t \t \t \t \t // $这 - >置( 'ERR_MSG', “无效的XML文件”); \t \t \t \t \t \t \t echo“Invalid”; \t \t \t \t \t \t \t exit; \t \t \t \t \t \t} – Sundar

+1

这是警告,而不是例外。你不能用try {} catch {}块来“捕捉”它们。 – hakre

回答

1

您的脚本正在加载文件。但是,该文件不能被解析为XML。

要停止警告被自动吐出到页面上(它会做这个,无论你是否try/catch语句),你需要使用:

libxml_use_internal_errors(true); 

之前处理任何类使用libxml。

Description从PHP.net:

libxml_use_internal_errors - 允许您禁用标准的libxml错误,并启用用户错误处理。

+0

通过使用这个libxml_use_internal_errors(true);页面显示为空。 – Sundar

+0

如何将错误消息作为无效的xml文件传递给用户。 – Sundar

+0

libxml_get_errors() –

1

如果您想尝试/发现警告,您必须将警告'转换'为异常。

设置您的全局错误处理是这样的:

set_error_handler('error_handler'); 

,然后警告转换为例外:

function error_handler($errno, $errmsg, $filename, $linenum, $vars) 
    { 
    // error was suppressed with the @-operator 
    if (0 === error_reporting()) 
     return false; 

    if ($errno !== E_ERROR) 
     throw new \ErrorException(sprintf('%s: %s', $errno, $errmsg), 0, $errno, $filename, $linenum); 

} 
+0

更好的方法是使用libxml_use_internal_errors(true),它允许您自己处理错误。 –