Tuesday, December 7, 2010

Grab Yahoo Stock Data streamerapi version

Grab Yahoo Stock Data streamerapi version

Method 1:

$STR = file_get_contents('tmp.txt');

$matchArr = NULL;

preg_match('/parent.yfs_u1f\((.*)\);/', $STR, $matchArr);

if (!empty($matchArr[1])) {
  $ARR = json_decode_v2($matchArr[1]);

  echo '
  echo '
'; } function _grab_yahoo_stock_index_streamerapi($symbol) { $URL = 'http://streamerapi.finance.yahoo.com/streamer/1.0?s=' . $symbol; // l10 // index value // c10 // change value // p20 // change percentage // g00 // day range low // h00 // day rang high // v00 // volume $URL_field = '&k=c10,g00,h00,l10,p20,v00'; $URL_postfix = '&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb'; $URL = $URL . $URL_field . $URL_postfix; # When using CURLOPT_FILE, pass it the file handle that is open # for write only (eg fopen('blahblah', 'w')). If you also open # the file for reading (eg fopen('blahblah', 'w+')), curl will # fail with error 23. $fp = fopen('tmp.txt', 'w'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URL); # When you are using CURLOPT_FILE to download directly into a file # you must close the file handler after the curl_close() otherwise # the file will be incomplete and you will not be able to use it # until the end of the execution of the php process. curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_TIMEOUT, 3); //curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_exec($ch); curl_close($ch); # at this point your file is not complete and corrupted. fclose($fp); return; } function json_decode_v2($json, $assoc = FALSE){ $json = str_replace(array("\n","\r"), "", $json); //$str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix variable names $json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/', '$1"$3":', $json); return json_decode($json, $assoc); } ?>

Method 2:
Set PHP curl option, but it doesn't work for me.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Method 3:
Run this in command line (you need curl installed on your system):
curl -s -o - -N 'http://streamerapi.finance.yahoo.com/streamer/1.0?s=^DJI&k=c10,g00,h00,l10,p20,v00&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb'


paulv8 said...

Great, love it!!!

You saved me a bunch on time.


p.s. typo in function name '_str'

Sharon Abu said...

the regexp isolates the json of a single qoute, but when you ftech more than one symbol it doesnt work, can you update it to fetch several quotes in one request?

Sharon Abu said...

preg_match('/parent.yfs_u1f\((.*)\);/', $STR, $matchArr);

works weel for fetching a single quote but not when you fetch several quotes in one request, can you update it to work for multiple quotes?

Mark J. Guillen said...

This program seems to be the perfect way to Grab Yahoo Stock Data.. Thanks for such incredible way.