开发者

Timing out a script portion and allowing the rest to continue

开发者 https://www.devze.com 2023-02-08 12:02 出处:网络
I have a widget that runs on my homepage which is loading xml data from an external source. I want to timeout the xml load after x seconds (lately the other site has been having load issues).Here is t

I have a widget that runs on my homepage which is loading xml data from an external source. I want to timeout the xml load after x seconds (lately the other site has been having load issues). Here is the function I have so far.开发者_StackOverflow I can't figure out how to make the timer ineract with the simplexml_load_file().

Am I on the right track? Is there a way to make this work? Or is there a better way to do this? If this does timeout, I still need the rest of the page to continue loading, so I can't use set_time_limit(), because that will end all script execution, right?

function timer($end) {
    $count = 0;
    while($end > $count) {
        sleep(1);
        $count++;
    }
    return true;
}

$we = simplexml_load_file('http://forecast.weather.gov/MapClick.php?lat=44.08920&lon=-70.17250&FcstType=xml');
if(timer(3)) return;


So you want to set a timeout for simplexml_load_file(). You can't set it specifically, but you can just set it globally (for all socket based streams) before using the function:

ini_set('default_socket_timeout', 3);
$we = simplexml_load_file($url);

// you can restore the default value after use, if you want
ini_restore('default_socket_timeout');


I would use CURL instead of loading the URL directly...

function getXml($url, $timeout = 0){
  $ch = curl_init($url);

  curl_setopt_array($ch,array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => (int) $timeout
  ));

  if($xml = curl_exec($ch)){
    return new SimpleXmlElement($xml);
  }
  else {
    return null;
  }
}

//Example
$xmlData = getXml('http://yoururl.com', 2); // 2 second timeout


You could first read the content of the file with some blocking or more reliable function (like fopen, fsockopen or curl, choose the best you can use) and then pass the content to simplexml_load_string instead of simplexml_load_file

0

精彩评论

暂无评论...
验证码 换一张
取 消