PHP从URL获取CSV,加载到数组中,格式 [英] PHP get CSV from URL, load into array, format
问题描述
我正在尝试编写一个脚本,以CSV格式从Yahoo Finance下载历史数据.我的脚本已成功将数据加载到数组中,但是遇到了两个问题.首先是尽管创建了一个从yahoo提取日期的日期范围,但我一直在获取该股票的全部历史数据,但我不确定为什么,我只希望从当日算起最近的6个月.其次,我能够使用str_getcsv将数据加载到数组中,但是我无法创建一个循环来将其设置到表中,第一行是表列的标题,其余的行则井井有条按日期按行排列.
I am trying to write a script to download historic data from yahoo finance as a csv. My script successfully loads the data into an array but I've run into two problems. First is that despite creating a date range for it to pull from yahoo, I keep getting the entire historical data for that stock and I'm not sure why.I only want the last 6months calculated back from current day. Second, I was able to use str_getcsv to load the data into an array, however I have been unable to create a loop that will work to set it up in a table with the first row being the headers of the table columns and the rest organized by date in rows.
这是代码:
<?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
等...
任何帮助将不胜感激!
推荐答案
您错过了b=e
中网址中的美元符号.这是将其分行获取的代码:
You missed the dollar sign in the url in b=e
. And here is the code to get it in rows:
$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);
}
这篇关于PHP从URL获取CSV,加载到数组中,格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!