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:

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 = "". $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);

//The data will be in the format:

//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 text area 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);

You can get stock data from Yahoo from the following URL:$stock&f=$format

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


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 *