Real Time Stock Quotes with PHP

I wanted to create a custom widget to put in a website that pulls and formats stock data in real time. I came across Micro Stock, a free PHP script that does just that. This script was ok, but the code was written for PHP4 and not very flexible.

I decided to write my own script instead. I went with Google Finance, since it has the added bonus of correcting misspellings. Here is the function getStockInfo($url) that parses stock information from the passed url.

function getStockInfo($url){

  //Load content from passed url into $page variable
  $page = file_get_contents($url);
  
  // Get company name and stock symbol
    //Search and place matches in array
    preg_match("/<h1>([^<]*)<\/h1>[\s]* [\s]*\([a-zA-z]*,([^\)]*)\)/",$page,$temp);
    if(count($temp)>1) //If name found
      list(,$name,$symbol) = $temp;
    else //No name found
      list($name,$symbol) = array('Unknown','');

  // Get other info
    //Define reusable regular expressions
    $decimal = '[0-9]+[\.]?[0-9]*'; //Matches a decimal number
    $span_id = '[^"]*'; //Matches dynamic span ids used by google
    $span_class = 'ch[grb]'; //Matches classes for colored text
    
    //Long regular expression to match price and changes in price
    preg_match('/<span class="pr" id="'.$span_id.'">('.$decimal.')<\/span><br>\n<span class=bld><span class="'.$span_class.'" id="'.$span_id.'">([\+\-]?)('.$decimal.')<\/span><\/span>\n<span class="'.$span_class.'" id="'.$span_id.'">\([\+\-]?('.$decimal.')%\)<\/span>/',$page,$text);

/*  $text holds formatted info
    $price holds the price in dollars
    $dir holds the direction of change ("+" or "-")
    $diff holds the change amount in dollars
    $percent holds the change amount in percent */ 

    if(count($text)>1)// Info found
      list($text,$price,$dir,$diff,$percent) = $text;
    else// No info found, fill with dummy data
      list($text,$price,$dir,$diff,$percent) = array('-','-','','','-');
    
    //Store data in array and return
    $result['name']  = $name;
    $result['symbol'] = trim($symbol);
    $result['price'] = $price;
    $result['diff']  = $diff;
    $result['percent'] = $percent;
    $result['dir'] = $dir;
    $result['text']  = $text;
    
    //Return array of data
    return $result;
}

The process is fairly straight forward. First, load the page into a variable. Then, pick out key data by searching for unique patterns.

The second step was the hardest part to do. I first looked at the source of a few Google Finance pages and found recurring patterns. I then translated those patterns into regular expressions, capturing the data I wanted to keep.

My example function only works with Google Finance, but the regular expressions could be altered to work with other sites.

Below is the return value when called with the following url: http://finance.google.com/finance?q=goog

Array
(
    [name] => Google Inc.
    [symbol] => NASDAQ:GOOG
    [price] => 442.93
    [diff] => 9.07
    [percent] => 2.09
    [dir] => +
    [text] => <span class="pr" id="ref_694653_l">442.93</span><br>
<span class=bld><span class="chg" id="ref_694653_c">+9.07</span></span>
<span class="chg" id="ref_694653_cp">(2.09%)</span>
)

This gives you the option of using pre-formatted text, but also gives you all the information you need to format it yourself. To see an example of this script in action, go to http://jeremydorn.com/demos/stocks.php

1 comments:

Supratik said...

I am trying the same now, not working.

preg_match is not returning the name...