2011-02-01 41 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'); 
相關問題