Twitter

PHP stock information example

Hereby an easy example how you can use the finance.yahoo.com webservice to fetch stock exchange information with PHP.


	function warquest_stockarray($data,$delim=',',$enclosure='"') {
		$enclosed=false;
		$fldcount=0;
		$linecount=0;
		$fldval='';
		for($i=0;$i<strlen($data);$i++) {
			$chr=$data{$i};
			switch($chr)
			{
				case $enclosure:
					if($enclosed&&$data{$i+1}==$enclosure) {
						$fldval.=$chr;
						++$i; 
					} else {
						$enclosed=!$enclosed;
					}
					break;
   
				case $delim:
					if(!$enclosed) {
						$ret_array[$linecount][$fldcount++]=$fldval;
						$fldval='';
					} else {
						$fldval.=$chr;
					}
					break;
				
				case "\r":
					if (!$enclosed&&$data{$i+1}=="\n") continue;
					
				case "\n":
					if(!$enclosed) {
						$ret_array[$linecount++][$fldcount]=$fldval;
						$fldcount=0;
						$fldval='';
					} else {
						$fldval.=$chr;
					}
					break;
				
				default:
					$fldval.=$chr;
			}
		}
		if($fldval) {
			$ret_array[$linecount][$fldcount]=$fldval;
		}
		return $ret_array;
	}

	function warquest_stock($stocksymbols) {		
		$url = sprintf("http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=snl1d1t1c1ohgvp", $stocksymbols);
		$data = file_get_contents($url);
	
		$stocklist=warquest_stockarray($data);
	
		for($i=0;$i<count($stocklist);$i++) {
		
			$stocksymbol=trim($stocklist[$i][0], '\"');
			$stock[$stocksymbol]["stocksymbol"] = 
			$stock[$stocksymbol]["company"] = trim($stocklist[$i][1], '\"');
			$stock[$stocksymbol]["last"] = $stocklist[$i][2];
			$stock[$stocksymbol]["date"] = trim($stocklist[$i][3], '\"');	
			$stock[$stocksymbol]["time"] = trim($stocklist[$i][4], '\"');					
			$stock[$stocksymbol]["change"] = $stocklist[$i][5];
			$stock[$stocksymbol]["open"] = $stocklist[$i][6];
			$stock[$stocksymbol]["high"] = $stocklist[$i][7];
			$stock[$stocksymbol]["low"] = $stocklist[$i][8];
			$stock[$stocksymbol]["volume"] = $stocklist[$i][9];
			$stock[$stocksymbol]["prevclose"] = $stocklist[$i][10];	
		}
		return $stock;
	}
	
	print_r(warquest_stock("DB"));


Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>