鍍金池/ 問(wèn)答/PHP/ PHP如何判斷simplexml_load_file失?。慷皇侵苯訄?bào)錯(cuò)

PHP如何判斷simplexml_load_file失???而不是直接報(bào)錯(cuò)

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

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

官方的說(shuō)明是 simplexml_load_file失敗返回false,但我這樣做了,還是報(bào)了個(gè)警告的錯(cuò)誤:拋出一些錯(cuò)誤信息,破壞我的json輸出:

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

注意,我不是查這個(gè)錯(cuò)誤原因,我知道這原因,我是想問(wèn)大神,如何捕獲這個(gè)錯(cuò),自己處理掉,而不是直接報(bào)錯(cuò)。但判斷返回值是不是false不生效。

回答
編輯回答
筱饞貓

針對(duì) warning,
我想到了兩種方法:

  • 添加錯(cuò)誤抑制符 @

    $xmlElement = @simplexml_load_file($ntp_file);
  • 控制 warning 輸出范圍
    通過(guò)控制 php.iniwarning 只在 日志里輸出,即:將 display_errors 值,改為 Off
    參考:PHP 運(yùn)行時(shí)配置-display_errors

2018年7月14日 06:41
編輯回答
帥到炸
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());
}
2017年4月3日 19:44