Home » Php » PHP get CSV from URL, load into array, format

PHP get CSV from URL, load into array, format

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

Here is the code:

<?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>';
?>

and here is the output:

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

etc…

Any help would be greatly appreciated!

How to&Answers:

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);
}

Answer:

PHP_EOL or “\n” may end $rows unexpectedly if new line exists .

$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);