tags:

views:

1167

answers:

2

Im using the following code:

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:[email protected]/account/rate_limit_status.xml");
$left = $xml->{"remaining-hits"};
$total = $xml->{"hourly-limit"};
return $left."/".$total;
}

and getting these errors when the stream cant connect:

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://[email protected]/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"

How can i handle these errors so i can display a user friendly message instead of whats shown above?

A: 

The documentation says that in the case of an error, simplexml_load_file returns FALSE. So, you can use the "shut-up" operator (@) in combination with a conditional statement:

if (@simplexml_load_file($file))
{
    // continue
}
else 
{
    echo 'Error!';
}
Ignas R
Not the shut-up not the shut up, please !
mere-teresa
so something like this? function GetTwitterAvatar($username){if(@simplexml_load_file("http://twitter.com/users/".$username.".xml")){$xml = simplexml_load_file("http://twitter.com/users/".$username.".xml");$imgurl = $xml->profile_image_url;return $imgurl;} else {return 'error';}}
Patrick
You can do it without calling simplexml_load_file twice: $xml = @simplexml_load_file("..."); if ($xml) { ... } else { return 'Error'; }
Ignas R
mere-teresa, but he needs to suppress the warning here... Of course, you can also use the display_errors setting or convert errors to exceptions and then use try/catch, but this is much simpler...
Ignas R
A: 

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

And Twitter is down, maybe ?

mere-teresa