2011-02-01 38 views
1

我有一个运行在我的主页上的小部件,它从外部源加载xml数据。我想在x秒后超时xml负载(最近其他站点一直有负载问题)。这是我迄今为止的功能。我无法弄清楚如何使计时器与simplexml_load_file()一致。定时执行脚本部分并允许其余部分继续

我在正确的轨道上吗?有没有办法做到这一点?还是有更好的方法来做到这一点?如果这样做超时,我仍然需要在页面的其余部分继续加载,所以我不能使用set_time_limit(),因为那会结束全部脚本执行,对吗?

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; 
+0

计时器(3)将使用simplexml_load_file后开始()完成。取决于simplexml_load_file()的行为,睡眠可能只会在下载xml文件后执行。 – Spliffster 2011-02-01 19:46:35

+0

@Spliff,我知道,但我不知道如何防止这种情况。 – JakeParis 2011-02-01 20:51:59

回答

3

我会用,而不是直接加载的URL卷曲...

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 
0

你可以先阅读该文件的一些阻塞或更可靠的功能操作(像fopen,或的fsockopen卷曲内容选择您可以用最好的),然后将内容传递给simplexml_load_string代替使用simplexml_load_file

4

所以,你要为超时。在使用功能前,不能设置它专门的,但你可以设置全局(针对所有基于socket流):

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'); 
相关问题