Showing posts with label php stock quotes. Show all posts
Showing posts with label php stock quotes. Show all posts

Stock Quotes with PHP

Yahoo! Finance provides quotes of virtually any stock in CSV format - all you need to supply is its ticker symbol. This is great for PHP developers who want to display quotes on a finance related website.

Now for a function that makes getting stock quotes feel like child's play:



function getQuote($symbol)
{

$symbol = urlencode( trim( substr(strip_tags($symbol),0,7) ) );
$yahooCSV = "http://finance.yahoo.com/d/quotes.csv?s=$symbol&f=sl1d1t1c1ohgvpnbaejkr&o=t";

$csv = fopen($yahooCSV,"r");

if($csv)
{
list($quote['symbol'], $quote['last'], $quote['date'], $quote['timestamp'], $quote['change'], $quote['open'],
$quote['high'], $quote['low'], $quote['volume'], $quote['previousClose'], $quote['name'], $quote['bid'],
$quote['ask'], $quote['eps'], $quote['YearLow'], $quote['YearHigh'], $quote['PE']) = fgetcsv($csv, ',');

fclose($csv);

return $quote;
}
else
{
return false;
}
}


The function returns an array of the stock's information. Here is a sample PHP script that uses the above function to display all the available stock information about the Royal Bank of Scotland (Ticker: RBS.L).


$RBSQuote = getQuote("RBS.L"); //Returns an array of stock information

echo "Symbol ".$RBSQuote['symbol']."<br/>";
echo "Last ".$RBSQuote['last']."<br/>";
echo "Date ".$RBSQuote['date']."<br/>";
echo "Timestamp ".$RBSQuote['timestamp']."<br/>";
echo "Change ".$RBSQuote['change']."<br/>";
echo "Open ".$RBSQuote['open']."<br/>";
echo "High ".$RBSQuote['high']."<br/>";
echo "Low ".$RBSQuote['low']."<br/>";
echo "Volume ".$RBSQuote['volume']."<br/>";
echo "Previous Close ".$RBSQuote['previousClose']."<br/>";
echo "Name ".$RBSQuote['name']."<br/>";
echo "Bid ".$RBSQuote['bid']."<br>";
echo "Ask ".$RBSQuote['ask']."<br/>";
echo "EPS ".$RBSQuote['eps']."<br/>";
echo "Year High ".$RBSQuote['YearLow']."<br/>";
echo "Year Low ".$RBSQuote['YearHigh']."<br/>";
echo "PE ".$RBSQuote['PE'];



A pretty nifty piece of code that adds extra utility to your website. I like it because it's simple and concise.

A PHP class called PHPQUOTE is available at Booyah Media that is capable of performing the same task as above in a more object orientated way. PHPQUOTE Download