For the last week or so, I have been looking for a good real time stock ticker to put up on a client’s web site since their feed with Yahoo kept failing intermittently. About 30% of the time, it would return an error that read “Received Failure” which while amusing, the client didn’t want to have anything to do with it.
So I spent a few hours going to different sites to see if they had a feed and none would give me what I wanted. All I needed was the current price, value change, percentage change and time last updated. Seemed impossible. Then I had the idea to just scrape data from Google’s Financial site and the rest is history.
I found this PHP project called PHP Simple HTML DOM Parser and used it in my code. Super simple.
include('simple_html_dom.php'); $tickerCID = '22144'; //This is Apple (AAPL) ticker ID on Google $stockSymbol = 'AAPL'; $html = file_get_html('https://www.google.com/finance?q=NASDAQ:' . $stockSymbol); $price = $html->find('span[id=ref_' . $tickerCID . '_l]', 0); $lasttrade = $price->plaintext; $spanChange = $html->find('span[id=ref_' . $tickerCID . '_c]', 0); $change = $spanChange->plaintext; $spanPercChange = $html->find('span[id=ref_' . $tickerCID . '_cp]', 0); $percChange = $spanPercChange->plaintext; $rightNowDate = date("M j"); $quoteTime = $html->find('span[id=ref_' . $tickerCID . '_ltt]', 0); $rightNow = $rightNowDate . ' ' . $quoteTime->plaintext; |
Then when I need to access that data, I just have this DIV in the body:
<div id="stockTick"> <p>NASDAQ: AAPL</p> <p style="font-size:10px;">$<?php echo $lasttrade; ?> <?php echo $change; ?><?php echo $percChange; ?> <?php echo $rightNow; ?></p> </div> |
It was that easy once I got the hang of it. Hope this can help someone with the same crap I had to go through.