2017-04-06 72 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