PHP从URL获取CSV,加载到数组,格式

时间:2014-10-13 20:03:22

标签: php arrays loops csv

我正在尝试编写一个脚本,以便从yahoo finance下载历史数据作为csv。我的脚本成功将数据加载到数组中,但我遇到了两个问题。首先,尽管创建了一个从雅虎拉出的日期范围,我仍然获得该股票的整个历史数据,我不知道为什么。我只希望从当天开始计算最后6个月。其次,我能够使用str_getcsv将数据加载到数组中,但是我无法创建一个循环,可以将其设置在一个表中,第一行是表列的标题,其余的是有组织的按日期排成行。

以下是代码:

<?php

$stock = "AAPL";
$date = strtotime(date('Y-m-d') . ' -1 month');
$date2 = strtotime(date('Y-m-d') . ' -6 months');

$a = (date('m', $date));
$b = (date('d', $date));
$c =(date('Y', $date));
$d = (date('m', $date2));
$e = (date('d', $date2));
$f =(date('Y', $date2));

 $s = str_getcsv(file_get_contents("http://ichart.yahoo.com/table.csv?s=$stock&a=$d&b=e&c=$f&d=$a&e=$b&f=$c&g=d"));


Stock:echo $stock;

echo '<pre>';
print_r($s);
echo '</pre>';
?>

这是输出:

AAPL

Array
(
    [0] => Date
    [1] => Open
    [2] => High
    [3] => Low
    [4] => Close
    [5] => Volume
    [6] => Adj Close
2014-10-10
    [7] => 100.69
    [8] => 102.03
    [9] => 100.30
    [10] => 100.73
    [11] => 66270200
    [12] => 100.73
2014-10-09
    [13] => 101.54
    [14] => 102.38
    [15] => 100.61
    [16] => 101.02
    [17] => 77312200
    [18] => 101.02
2014-10-08
    [19] => 98.76
    [20] => 101.11
    [21] => 98.31
    [22] => 100.80
    [23] => 57364800
    [24] => 100.80
2014-10-07
    [25] => 99.43
    [26] => 100.12
    [27] => 98.73
    [28] => 98.75
    [29] => 42068200
    [30] => 98.75

等...

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:6)

您错过了b=e中网址中的美元符号。这是获取行的代码:

$data = file_get_contents("http://ichart.yahoo.com/table.csv?s=$stock&a=$d&b=$e&c=$f&d=$a&e=$b&f=$c&g=d");
$rows = explode("\n",$data);
$s = array();
foreach($rows as $row) {
    $s[] = str_getcsv($row);
}

答案 1 :(得分:3)

如果存在新行,

PHP_EOL &#34; \ n&#34; 可能会意外终止$rows

$file = "http://ichart.yahoo.com/table.csv?s=$stock&a=$d&b=$e&c=$f&d=$a&e=$b&f=$c&g=d";

$fileData=fopen($file,'r');
while (($line = fgetcsv($fileData)) !== FALSE) {

   $s[] = $line;
}
echo "<pre>";
var_dump($s);