Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Forked from robflaherty/csv-to-json.php
Created June 27, 2012 20:58
Show Gist options
  • Save timelyportfolio/3006804 to your computer and use it in GitHub Desktop.
Save timelyportfolio/3006804 to your computer and use it in GitHub Desktop.
Convert Yahoo Finance CSV to JSON for use with d3.js
<?php
/*
* Converts CSV to JSON
* Example uses Google Spreadsheet CSV feed
* csvToArray function I think I found on php.net
*/
header('Content-type: application/json');
// Set your CSV feed
$ticker = $_GET["ticker"];
$month = intval($_GET["month"]) - 1;
$day = intval($_GET["day"]);
$year = intval($_GET["year"]);
$feed = 'http://ichart.finance.yahoo.com/table.csv?s=' . $ticker . '&a=' . $month . '&b=' . $day . '&c=' . $year . '&g=d&ignore=.csv';
// Arrays we'll use later
$keys = array();
$newArray = array();
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
// Do it
$data = csvToArray($feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
// Add Ids, just in case we want them later
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
// Print it out as JSON
echo json_encode($newArray);
?>
@timelyportfolio
Copy link
Author

thanks so much for your example; I changed very minimally to return json from yahoo finance historical data so I can use in d3.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment