Skip to content

Instantly share code, notes, and snippets.

@dmalan
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmalan/e13e8e72a2556643a93a to your computer and use it in GitHub Desktop.
Save dmalan/e13e8e72a2556643a93a to your computer and use it in GitHub Desktop.
/**
* 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