首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >simplexml错误处理php

simplexml错误处理php
EN

Stack Overflow用户
提问于 2009-08-20 16:13:35
回答 5查看 64.4K关注 0票数 28

我使用了以下代码:

代码语言:javascript
复制
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;
}

并在流无法连接时获得这些错误:

代码语言:javascript
复制
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"

我如何处理这些错误,才能显示用户友好的消息,而不是上面显示的消息?

EN

回答 5

Stack Overflow用户

发布于 2011-01-03 16:59:34

我认为这是一个更好的方法

代码语言:javascript
复制
$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);

更多信息:http://php.net/manual/en/function.libxml-use-internal-errors.php

票数 48
EN

Stack Overflow用户

发布于 2013-04-17 13:17:15

如果你看一下手册,就会发现有一个选项参数:

代码语言:javascript
复制
SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

提供选项列表:http://www.php.net/manual/en/libxml.constants.php

这是抑制解析警告的正确方法:

代码语言:javascript
复制
$xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);
票数 9
EN

Stack Overflow用户

发布于 2015-11-23 23:07:02

这是一个古老的问题,但在今天仍然是相关的。

使用oop SimpleXMLElment时处理异常的正确方法如下所示。

代码语言:javascript
复制
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.
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1307275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档