tags:

views:

29

answers:

1

I'm using domdocument load to fetch some data. On occasion, this data is not available and when the script runs, I will get errors or warnings. I noticed that I can test for a return value if the data is not there. Is it best to use a while loop or an if statement?

A: 

I'm assuming you are trying to load a remote document, and that's why it is occasionally unavailable. I suggest trying the following:

<?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);
}

This could also be written as a for loop of course. It doesn't really matter.

hobodave
Thank you hobodave. This was exactly the construct that I was looking for.
BiBo
Hey hobo.. can I ask you a question about this? I've never seen a variable preceeded by plus signs. What is that?
BiBo
BiBo: http://www.php.net/manual/en/language.operators.increment.php
hobodave
Thanks! Will go there now.
BiBo