Saturday, March 28, 2009

Accessing Yahoo! Finance from PHP

How to Use PHP to Obtain Stock Quotes from Yahoo! Finance


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:

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

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

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);
?>

If this code is stored in a file (for example yahoo_finance_lookup.php) then it can be called from a form:



No comments:

Post a Comment