I have several requirement which are listed below.
- Get Real Time stock price without page refresh or ajax. (ie. yahoo finance, they get latest stock price without page refresh and ajax call)
- Get stock price from as much as stock market like BSE, NSC etc..
Right now using following code i am able to get stock price but either i have to refresh the page or call to ajax and in both case it take 20 to 30 seconds but in many finance site they can update price by each second without using ajax.
<?php
/**
* Class to fetch stock data from Yahoo! Finance
*
*/
class YahooStock {
/**
* Array of stock code
*/
private $stocks = array();
/**
* Parameters string to be fetched
*/
private $format;
/**
* Populate stock array with stock code
*
* @param string $stock Stock code of company
* @return void
*/
public function addStock($stock)
{
$this->stocks[] = $stock;
}
/**
* Populate parameters/format to be fetched
*
* @param string $param Parameters/Format to be fetched
* @return void
*/
public function addFormat($format)
{
$this->format = $format;
}
/**
* Get Stock Data
*
* @return array
*/
public function getQuotes()
{
$result = array();
$format = $this->format;
foreach ($this->stocks as $stock)
{
/**
* fetch data from Yahoo!
* s = stock code
* f = format
* e = filetype
*/
$s = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=$format&e=.csv");
/**
* convert the comma separated data into array
*/
$data = explode( ',', $s);
/**
* populate result array with stock code as key
*/
$result[$stock] = $data;
}
return $result;
}
}
$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");
$objYahooStock->addStock("FB");
/**
* Printing out the data
*/
?>
<table width="100%">
<tr>
<th>Row</th>
<th>Code</th>
<th>Name</th>
<th>Last Trade Price</th>
<th>Last Trade Time</th>
<th>Change and Percent Change</th>
<th>Volume</th>
</tr>
<?php
foreach( $objYahooStock->getQuotes() as $code => $stock)
{
?>
<tr>
<td><?php //print_r($stock); ?></td>
<td><?php echo $stock[0]; ?></td>
<td><?php echo $stock[1]; ?></td>
<td><?php echo $stock[2]; ?></td>
<td><?php echo $stock[3]; ?></td>
<td><?php echo $stock[4]; ?></td>
<td><?php echo $stock[5]; ?></td>
<td><?php echo $stock[6]; ?></td>
</tr>
<?php
}
?>
</table>