How to Use PHP to Obtain Stock Quotes from Yahoo Finance

Home / PHP / How to Use PHP to Obtain Stock Quotes from Yahoo Finance

Yahoo! Finance is a very useful resource for both analysts and programmers alike.
A PHP library is created by saving the function into a text file – in this example the library is going to be called yahoo_finance.php and this will contain a single function:

<?php
function show_stock_quotes ($stock_list) {

//The function will, by default, return the details of some of the stock markets:
if (! $stock_list) {
$stock_list = "^IXIC,^DJA,^NIN,^FTSE";
}

//The function will then use either an input list or the default list to create the correct url:
$url = "http://quote.yahoo.com/d/quotes.csv?s=". $stock_list . "&f=nl1c1&e=.csv";

//and then read in the data stream from the Yahoo! Finance web site:
$filesize = 2000;
$handle = fopen($url, "r");
$raw_quote_data = fread($handle, $filesize);
fclose($handle);

//The data will be in the format:
"BSE-100",4.37,0.47
"ATX",23.23,-1.68

//and so the next stage is to load the data into an array (using the new line as a delimiter):
$quote_array = explode("\n", $raw_quote_data);

//finally the results can be output (taking care to remove the additional quotation marks):
echo "";
echo "";
$quote = explode(",", $quote_value);
$symbol = str_replace("\"", "", $quote[0]);
$value = $quote[1];
$change = $quote[2];
echo "";
echo "";

echo "
Name     Stock Quote     Change";
foreach ($quote_array as $quote_value) {
echo "
$symbol     $value     $change
";
}

}
?>

Using the PHP Function to Display Yahoo! Finance Data to your


Once the function and library have been saved then they can be used in a PHP web page (for instance index.php) to display the default stock market data:

<?php
include ("yahoo_finance.php");
show_stock_quotes (False);
?>

or used in a PHP file that can process the input from a text area box:

<?php
include ("yahoo_finance.php");
$symbol_list = str_replace("\n", ",", $_REQUEST["symbol_list"]);
$symbol_list = str_replace("\r", ",", $symbol_list);
show_stock_quotes (False);
show_stock_quotes ($symbol_list);
?>

You can get stock data from Yahoo from the following URL:

http://finance.yahoo.com/d/quotes.csv?s=$stock&f=$format

Here,
$stock = stock symbol (e.g. GOOG for Google, MSFT for Microsoft, APPL for Apple, etc.)
$format = format or tags to be fetched

Example,

http://finance.yahoo.com/d/quotes.csv?s=GOOG+AAPL+MSFT+YHOO&f=snl1d1t1cv

s = Symbol
n = Name
l1 = Last Trade (Price Only)
d1 = Last Trade Date
t1 = Last Trade Time
c = Change and Percent Change
v = Volume

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *