2017-04-06 67 views
0

我有陣列,例如獲取數據:最好的辦法從其他服務

$links = array(
    'http://aaa.com/data.txt', 
    'http://aaea.com/data.txt', 
    'http://aada.com/data.txt', 
    'http://agaa.com/data.txt', 
    'http://ahaa.com/data.txt', 
    'http://awha.com/data.txt', 
    'http://aaeha.com/data.txt', 
    //etc x100 
); 

而在PHP我做:

foreach ($links as $link) { 
    $data = file_get_contents($link); 
    //save data in database 
} 

它工作正常,但非常緩慢。用PHP做這個更好的方法是什麼?我想讓數據異步。

我的另一種方式 - 從PHP腳本的jQuery和Ajax查詢,但也許存在更好的方式?

+0

PHP是單線程的(雖然有一些多線程庫),所以你將無法在腳本中非常容易地異步獲取。 其他選項包括緩存這些數據文件,並且只在它們過期時刷新它們(您可以從URL中獲取標題以嘗試查找日期時間)。 – fbas

+1

嘗試http://php.net/manual/en/function.curl-multi-exec.php – LiTe

+0

您可能會發現這有助於:http://stackoverflow.com/questions/15559157/understanding-php-curl-multi- exec –

回答

0

我會建議這樣做。

<?php 
$Links = array(
    'http://aaa.com/data.txt', 
    'http://aaea.com/data.txt', 
    'http://aada.com/data.txt', 
    'http://agaa.com/data.txt', 
    'http://ahaa.com/data.txt', 
    'http://awha.com/data.txt', 
    'http://aaeha.com/data.txt' 
); 
$TempData = ''; 
foreach ($Links as $Link) { 
    $TempData .= file_get_contents($Link); 
    $TempData .= '|'; 
} 
$Data = rtrim($TempData, '|'); 

// save the $Data string and when you export the 
// string from the db use this code to turn it into an array 
// 
// $Data = explode('|' $ExportedData); 
// var_dump($Data); 
// 
// If you do it this way you will be preforming 1 sql 
// statement instead of multiple saving site resources 
// and making you code execute faster 

?> 

如果這有助於讓我知道。

+0

當PHP必須等待來自遠程服務器的響應而不是多個數據庫查詢時,我認爲一個瓶頸是調用多個file_get_contents。 – LiTe