問題描述
在我的應用程序中,我從 url 加載 xml 以解析它.但有時這個 url 可能無效.在這種情況下,我需要處理錯誤.我有以下代碼:
In my application I am loading xml from url in order to parse it. But sometimes this url may not be valid. In this case I need to handle errors. I have the following code:
$xdoc = new DOMDocument();
try{
$xdoc->load($url); // This line causes Warning: DOMDocument::load(...)
// [domdocument.load]: failed to open stream:
// HTTP request failed! HTTP/1.1 404 Not Found in ...
} catch (Exception $e) {
$xdoc = null;
}
if($xdoc == null){
// Handle
} else {
// Proceed
}
我知道我可能做錯了,但是處理這種異常的正確方法是什么?我不想在我的頁面上看到錯誤消息.
I know I probably doing it wrong, but what's a correct way to handle this kind of exceptions? I don't want to see error messages on my page.
DOMDocument::load() 手冊說:
The manual for DOMDocument::load() says:
如果傳遞一個空字符串作為文件名或一個空文件被命名,一個將產生警告.這警告不是由 libxml 生成的,并且無法使用 libxml 的錯誤處理處理函數.
If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.
但是沒有關于如何處理它的信息.
But there is no information on how to handle it.
謝謝.
推薦答案
我可以從 文檔,處理此方法發出的警告很棘手,因為它們不是由 libxml 擴展生成的,因此無法由 libxml_get_last_error()
處理.您可以使用錯誤抑制運算符并檢查 false
...
From what I can gather from the documentation, handling warnings issued by this method is tricky because they are not generated by the libxml extension and thus cannot be handled by libxml_get_last_error()
. You could either use the error suppression operator and check the return value for false
...
if (@$xdoc->load($url) === false)
// ...handle it
...或注冊一個錯誤處理程序,它會在錯誤時引發異常:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
然后抓住它.
這篇關于PHP DOMDocument 錯誤處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!