猿问

PHP如何判断simplexml_load_file失败?而不是直接报错

大神们好,我的程序使用如下方式 读取XML:

        $xmlElement = simplexml_load_file($ntp_file);
        if ($xmlElement == false) {
            $this->set_error(101100, "parse_ntp_file_error!");
            return false;
        }

官方的说明是 simplexml_load_file失败返回false,但我这样做了,还是报了个警告的错误:抛出一些错误信息,破坏我的json输出:

parser error : Input is not proper UTF-8, indicate encoding 

注意,我不是查这个错误原因,我知道这原因,我是想问大神,如何捕获这个错,自己处理掉,而不是直接报错。但判断返回值是不是false不生效。

Cats萌萌
浏览 401回答 2
2回答

POPMUISE

针对 warning,我想到了两种方法: 添加错误抑制符 @ $xmlElement = @simplexml_load_file($ntp_file); 控制 warning 输出范围通过控制 php.ini 让 warning 只在 日志里输出,即:将 display_errors 值,改为 Off参考:PHP 运行时配置-display_errors

侃侃无极

try{ $xmlElement = simplexml_load_file($ntp_file); if ($xmlElement == false) { $this->set_error(101100, "parse_ntp_file_error!"); return false; } } catch(\Exception $e) { $this->set_error( $e->getCode(), $e->getMessage()); return false; } catch(\Error $e) { $this->set_error( $e->getCode(), $e->getMessage()); }
随时随地看视频慕课网APP
我要回答