domdocument加载错误。如何测试

时间:2010-01-09 18:22:16

标签: php

我正在使用domdocument load来获取一些数据。有时,这些数据不可用,当脚本运行时,我会收到错误或警告。我注意到如果数据不存在,我可以测试返回值。是否最好使用while循环或if语句?

1 个答案:

答案 0 :(得分:0)

假设您正在尝试加载远程文档,这就是它偶尔无法使用的原因。 我建议尝试以下方法:

<?php
$dom = new DOMDocument();

$tries = 0;
$retryLimit = 10; // # of times to try loading
$interval = 2;    // wait time between attempts (seconds);
while ( !$dom->load('http://www.example.com/') ) {
    if (++$tries > $retryLimit) {
        throw new Exception("Unable to load remote document");
    }
    sleep($interval);
}

当然,这也可以写成for循环。这并不重要。