如何使用雅虎财务获得RealTime股票价格

Dip*_*pen 5 php ajax jquery yahoo-finance

我有几个要求,如下所列.

  1. 获取实时股票价格,无需刷新页面或ajax.(即雅虎财经,他们获得最新的股票价格,没有页面刷新和ajax调用)
  2. 从像BSE,NSC等股票市场获得股票价格.

现在使用以下代码我能够获得股票价格,但要么我必须刷新页面或调用ajax,在这两种情况下需要20到30秒,但在许多财务网站,他们可以每秒更新价格而不使用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>
Run Code Online (Sandbox Code Playgroud)

Dog*_*las 5

<?php

class U_Yahoo{

    private function file_get_contents_curl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_URL, $url);

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    //return the history quote from the simbol, default begin date is 90 day ago, the default end is today
    public function getHistoryQuote($symbol, $begin = 90, $end = 0){
        if(!$begin && !$end)
            $begin = $end = 0;

        $begin = Date('Y-m-d', strtotime("-{$begin} days"));
        $end = Date('Y-m-d', strtotime("-{$end} days"));
        $url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22$symbol%22%20and%20startDate%20%3D%20%22$begin%22%20and%20endDate%20%3D%20%22$end%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
        $jason_obj = json_decode( $this->file_get_contents_curl($url) );
        return $jason_obj->query->results->quote;
    }

    //return not just the quote but others informations too
    public function getCurrentData($symbol){
        $is_array = is_array($symbol);

        $imp_symbol = ($is_array)? implode('%22%2C%22', $symbol) : $symbol;

        $url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22$imp_symbol%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
        $jason_obj = json_decode( $this->file_get_contents_curl($url) );

        $result = $jason_obj->query->results->quote;

        return (is_array($symbol) and (count($symbol) == 1))? [$result] : $result;
    }

    //return all quotes from the param $symbol passed, if symbol is array, it will return other array indexed by the symbols
    public function getCurrentQuote($symbol){
        if(is_array($symbol)){
            $symbol = empty($symbol)? ['GOOG'] : $symbol;
            $data = $this->getCurrentData($symbol);
            $result = [];

            for ($c = 0; $c < count($data); $c++) { 
                $result[$data[$c]->Symbol] = $data[$c]->LastTradePriceOnly;
            }

            return $result;
        }else
            return $this->getCurrentData($symbol)->LastTradePriceOnly;
    }

}
Run Code Online (Sandbox Code Playgroud)

怎么用:

$yahoo = new U_Yahoo();
var_dump( $yahoo->getCurrentQuote('GOOG') );
var_dump( $yahoo->getCurrentQuote(['GOOG', 'YHOO']) );

var_dump( $yahoo->getCurrentData(['GOOG', 'YHOO']) );

var_dump( $yahoo->getHistoryQuote('YHOO', 20, 0) );
Run Code Online (Sandbox Code Playgroud)


Pix*_*xou 2

好吧,在您的方法中,股票价格获取是由客户端(用户的浏览器)触发的。所以没有办法在页面刷新或AJAX之外触发它。

但是,无论用户如何,您的服务器都可以获取这些数据。就像是:

data source <----> your backend server fetching the data ---> your database <---- your frontend web server <---> users
Run Code Online (Sandbox Code Playgroud)

后端和前端服务器可以是同一台服务器但具有不同的进程。