php:simplexml异常重试

时间:2010-04-16 15:31:39

标签: php exception-handling simplexml

我正在使用SimpleXML查询API,由于未知原因,它偶尔会失败。我想让脚本重试最多5次。我怎样才能做到这一点?我认为它与在try / catch中包装对象有关,但我对此并不十分熟悉 - 试图阅读有关异常处理的手册,但仍然不知所措。

感谢您的帮助:)

// set up xml handler
$xmlstr = file_get_contents($request);
$xml = new SimpleXMLElement($xmlstr);

以下是我收到的错误消息:

[function.file-get-contents]:无法打开流:HTTP请求失败!

3 个答案:

答案 0 :(得分:2)

尝试使用curl来获取您要解析的内容... file_get_contents可能会失败而没有太多解释。也试着不要使用@(这会隐藏你可以使应用程序死掉的错误),或者只是因为你可以隐藏警告而只能用错误的方式进行编码

答案 1 :(得分:0)

使用您描述的try ... catch的一种示例方式。这并不是真正处理错误,但重试了5次。我建议您尝试诊断导致间歇性故障的问题。

class MyClass {

    protected $xml;

    public function readAPI() {

        ...
        $loaded = false;
        $fetch = 5;

        while (!$loaded && $fetch) {
            $loaded = $this->_loadXML($request);
            $fetch--;
        }

    }

    protected function _loadXML($request) {

        $result = true;

        try {
            $xmlStr = file_get_contents($request);
            $this->xml = new SimpleXMLElement($xmlStr);
        } catch (Exception $e) {
            $result = false;
        }

        return $result;
    }
}

您可能希望再次抛出异常并将其捕获到调用代码的更高位置。

答案 2 :(得分:0)

try .. catch块不会捕获常规错误,但只会Exception,除非您将set_error_handler设置为将错误转换为ErrorExceptions.。看到问题所在在file_get_contents这样的事情可能是更好的选择(未经测试):

$maxTries = 5;
do
{
  // supress the error with @ (or log it) and probe the output in while condition
  $content = @file_get_content( $someUrl );
}
while( false === $content && --$maxTries );

if( false !== $content )
{
   try
   {
      // SimpleXMLElement *will* throw an exception in case of malformed xml
      $xml = new SimpleXMLElement( $content );
   }
   catch( Exception $exception )
   {
      /* handle exception */
   }
}
else
{
    /* handle file_get_contents failure */
}

但是,由于你试图从一个http url读取,我认为失败与ini设置有关,是否允许url请求打开文件。请参阅allow_url_fopen上的文档。是不是有人/某人现在改变这个设置呢?

报废......这是不太可能的,因为它不能在运行时设置(PHP> 4.3.4)。