Get Stock Data From Yahoo Finance in PHP

Welcome in s2ptech here i am giving you new web service for Yahoo Finance in php by which you can easily get stock quote data from Yahoo.
You need to follow some step:
  • Step 1: First of all i am giving you top tech companies data from Yahoo Finance.
  1. For eBay: http://finance.yahoo.com/q?s=EBAY
  2. For Amazon: http://finance.yahoo.com/q?s=AMZN
  3. For Apple: http://finance.yahoo.com/q?s=AAPL
  4. For Microsoft: http://finance.yahoo.com/q?s=MSFT
  5. For Yahoo: http://finance.yahoo.com/q?s=YHOO
You can use for more by finding stock ticker symbol like GOOG for Google, MSFT for Microsoft, APPL for Apple, etc.
  • Step 2: Now i am tell you How can you fetch data from giving url using PHP. You need to make two php file.

yahoofinance.php
<?php
class YahooStock {
     private $stocks = array();
     private $format;
     public function addStock($stock)
    {
        $this->stocks[] = $stock;
    }
     public function addFormat($format)
    {
        $this->format = $format;
    }
     public function getQuotes()
    {      
        $result = array();    
        $format = $this->format;
        
        foreach ($this->stocks as $stock)
        {          
           $s = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=$format&e=.csv");
                 $data = explode( ',', $s);
                 $result[$stock] = $data;
        }
        return $result;
    }
  • Step 3: Now make another php file


index.php (main php file)
<?php
include_once('yahoofinance.php ');

$objYahooStock = new YahooStock;

/**
    Add format/parameters 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
 */
$objYahooStock->addFormat("snl1d1t1cv");

/**
    Add company stock code to be fetched
    
    msft = Microsoft
    amzn = Amazon
    yhoo = Yahoo
    goog = Google
    aapl = Apple  
 */
$objYahooStock->addStock("msft");
$objYahooStock->addStock("amzn");
$objYahooStock->addStock("yhoo");
$objYahooStock->addStock("goog");
$objYahooStock->addStock("vgz");

/**
 * Printing out the data
 */
foreach( $objYahooStock->getQuotes() as $code => $stock)
{
    ?>
    Code: <?php echo $stock[0]; ?> <br />
    Name: <?php echo $stock[1]; ?> <br />
    Last Trade Price: <?php echo $stock[2]; ?> <br />
    Last Trade Date: <?php echo $stock[3]; ?> <br />
    Last Trade Time: <?php echo $stock[4]; ?> <br />
    Change and Percent Change: <?php echo $stock[5]; ?> <br />
    Volume: <?php echo $stock[6]; ?> <br /><br />
    <?php
}
?>
  •  Step 4: Just run index.php file and thats it.

Note: If you think it is valuable post then please give some time to comment and feel free to give suggestion.
0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment