为什么不使用 foreach?
<?php
$lists = array("GOOG", "AAP", "MSFT");
foreach($lists as $list)
{
echo "<h3>Values for ".$list."</h3>";
$fp = fopen ("http://finance.yahoo.com/d/quotes.csv?s=".$list."&f=sl1ve1x&e=.csv","r");
$data = fgetcsv ($fp, 1000, ",");
fclose($fp);
echo $data[0]."<br/>",
$data[1]."<br/>",
$data[2]."<br/>";
}
/* Result
Values for GOOG
GOOG
681.72
1582936
Values for AAP
AAP
80.44
1306227
Values for MSFT
MSFT
29.86
43408272
*/
?>
编辑:
您可能还想知道,使用 fopen 循环大约慢 4.6 倍,然后使用 curl_multi 作为 curl multi 将同时发出所有请求,结果如下:
简单卷曲多功能:
<?php
function curl_multi_get($data) {
$curly = array();
$result = array();
$mh = curl_multi_init();
foreach ($data as $id=>$d) {
$curly[$id] = curl_init();
curl_setopt($curly[$id], CURLOPT_URL, 'http://finance.yahoo.com/d/quotes.csv?s='.$d.'&f=sl1ve1x&e=.csv');
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curly[$id], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curly[$id], CURLOPT_TIMEOUT, 30);
curl_setopt($curly[$id], CURLOPT_AUTOREFERER, true);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $curly[$id]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
curl_multi_close($mh);
return $result;
}
?>
在0.50315880775452秒内卷曲多
<?php
//Benchmark test 1 curl_multi
$time_start = microtime(true);
//---------------------------------------
$lists = array("GOOG", "AAP", "MSFT");
$result = curl_multi_get($lists);
foreach($result as $data)
{
$data = explode(',',$data);
echo "<h3>Values for ".$data[0]."</h3>";
echo $data[0]."<br/>",
$data[1]."<br/>",
$data[2]."<br/>";
}
//--------------------------------------
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Curl multi in $time seconds\n";
//end first test
//Did Curl multi in 0.50315880775452 seconds
?>
fopen() 在2.3253791332245秒内
<?php
//Benchmark test 2 fopen()
$time_start = microtime(true);
//--------------------------------------
$lists = array("GOOG", "AAP", "MSFT");
foreach($lists as $list)
{
echo "<h3>Values for ".$list."</h3>";
$fp = fopen ("http://finance.yahoo.com/d/quotes.csv?s=".$list."&f=sl1ve1x&e=.csv","r");
$data = fgetcsv ($fp, 1000, ",");
fclose($fp);
echo $data[0]."<br/>",
$data[1]."<br/>",
$data[2]."<br/>";
}
//--------------------------------------
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did fopen() in $time seconds\n";
//end second test
//Did fopen() in 2.3253791332245 seconds
?>
希望能帮助到你