mrp*_*atg 23 php xml simplexml
我使用以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
并在流无法连接时收到这些错误:
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"
Run Code Online (Sandbox Code Playgroud)
如何处理这些错误,以便显示用户友好的消息而不是上面显示的消息?
Ale*_*lex 46
我认为这是一种更好的方式
$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);
Run Code Online (Sandbox Code Playgroud)
更多信息:http://php.net/manual/en/function.libxml-use-internal-errors.php
Bri*_*nti 20
我在php文档中找到了一个很好的例子.
所以代码是:
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (false === $sxe) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
Run Code Online (Sandbox Code Playgroud)
输出,正如我们/我预期的那样:
加载XML失败
Run Code Online (Sandbox Code Playgroud)Blank needed here parsing XML declaration: '?>' expected Opening and ending tag mismatch: xml line 1 and broken Premature end of data in tag broken line 1
如果查看手册,则有一个选项参数:
SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )
Run Code Online (Sandbox Code Playgroud)
选项列表可用:http://www.php.net/manual/en/libxml.constants.php
这是抑制警告解析警告的正确方法:
$xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);
Run Code Online (Sandbox Code Playgroud)
这是一个老问题,但今天仍然有意义。
使用oop SimpleXMLElment时处理异常的正确方法是这样的。
libxml_use_internal_errors(TRUE); // this turns off spitting errors on your screen
try {
$xml = new SimpleXMLElement($xmlStringOfData);
} catch (Exception $e) {
// Do something with the exception, or ignore it.
}
Run Code Online (Sandbox Code Playgroud)