simplexml错误处理php

我使用以下代码:

function GetTwitterAvatar($username){
$xml = simplexml_load_file("http://twitter.com/users/".$username.".xml");
$imgurl = $xml->profile_image_url;
return $imgurl;
}

function GetTwitterAPILimit($username, $password){
$xml = simplexml_load_file("http://$username:$password@twitter.com/account/rate_limit_status.xml");
$left = $xml->{"remaining-hits"};
$total = $xml->{"hourly-limit"};
return $left."/".$total;
}

并且当流无法连接时获取这些错误:

Warning: simplexml_load_file(http://twitter.com/users/****.xml) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://twitter.com/users/****.xml" 

Warning: simplexml_load_file(http://...@twitter.com/account/rate_limit_status.xml) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://***:***@twitter.com/account/rate_limit_status.xml"

我如何处理这些错误,所以我可以显示一个用户友好的消息,而不是上面显示的内容?

最佳答案
文档说在出现错误的情况下,simplexml_load_file返回FALSE。因此,您可以使用“关闭”运算符(@)与条件语句的组合:

if (@simplexml_load_file($file))
{
    // continue
}
else 
{
    echo 'Error!';
}

转载注明原文:simplexml错误处理php - 代码日志