Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplexml error handling php

Tags:

php

xml

simplexml

I am 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 cannot 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 what is shown above?

like image 416
mrpatg Avatar asked Aug 20 '09 16:08

mrpatg


1 Answers

I thinks this is a better way

$use_errors = libxml_use_internal_errors(true); $xml = simplexml_load_file($url); if (false === $xml) {   // throw new Exception("Cannot load xml source.\n"); } libxml_clear_errors(); libxml_use_internal_errors($use_errors); 

more info: http://php.net/manual/en/function.libxml-use-internal-errors.php

like image 98
Alex Avatar answered Sep 21 '22 01:09

Alex