Last active
August 29, 2015 14:05
-
-
Save dmalan/e13e8e72a2556643a93a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a stock by symbol (case-insensitively) else false if not found. | |
*/ | |
function lookup($symbol) | |
{ | |
// reject symbols that start with ^ | |
if (preg_match("/^\^/", $symbol)) | |
{ | |
return false; | |
} | |
// reject symbols that contain commas | |
if (preg_match("/,/", $symbol)) | |
{ | |
return false; | |
} | |
// headers for proxy servers | |
$headers = [ | |
"Accept" => "*/*", | |
"Connection" => "Keep-Alive", | |
"User-Agent" => sprintf("curl/%s", curl_version()["version"]) | |
]; | |
// open connection to Yahoo | |
$context = stream_context_create([ | |
"http" => [ | |
"header" => implode(array_map(function($value, $key) { return sprintf("%s: %s\r\n", $key, $value); }, $headers, array_keys($headers))), | |
"method" => "GET" | |
] | |
]); | |
$handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s=$symbol", "r", false, $context); | |
if ($handle === false) | |
{ | |
// trigger (big, orange) error | |
trigger_error("Could not connect to Yahoo!", E_USER_ERROR); | |
exit; | |
} | |
// download first line of CSV file | |
$data = fgetcsv($handle); | |
if ($data === false || count($data) == 1) | |
{ | |
return false; | |
} | |
// close connection to Yahoo | |
fclose($handle); | |
// ensure symbol was found | |
if ($data[2] === "0.00") | |
{ | |
return false; | |
} | |
// return stock as an associative array | |
return [ | |
"symbol" => $data[0], | |
"name" => $data[1], | |
"price" => $data[2], | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment