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
2010-01-09 18:40:18
Thank you hobodave. This was exactly the construct that I was looking for.
BiBo
2010-01-09 18:50:43
Hey hobo.. can I ask you a question about this? I've never seen a variable preceeded by plus signs. What is that?
BiBo
2010-01-09 18:52:31
BiBo: http://www.php.net/manual/en/language.operators.increment.php
hobodave
2010-01-09 18:56:04
Thanks! Will go there now.
BiBo
2010-01-09 18:57:51