Solved

Retrieving the current gold price (CGP) using PHP

Posted on 2010-09-01
5
2,211 Views
Last Modified: 2013-12-13
Does anyone here know how I might retrieve the current gold price (in US dollars) using PHP?  

Ideally, I'd like to see an example PHP script that retrieves the current gold price (from some kind of remote data feed provider, I'm assuming) and then displays it on the page.

Thanks,
- Yvan
0
Comment
Question by:egoselfaxis
  • 4
5 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33576240
Finding a reliable feed is your first issue.  Do you know of one?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33576275
Using this search, ...
http://lmgtfy.com/?q=Spot+Price+Gold

... I found this data source:
http://www.goldprice.org/

I'll post a script to give you the "scrape" of this page in just a moment.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 33576636
This was easier to scrape.  It is not real-time (none of the free information sources are) but it seems to get updated within a half hour or so.

Cheers, ~Ray
<?php // RAY_temp_egoselfaxis.php
error_reporting(E_ALL);

// SCRAPE THE PRICE OF GOLD OUT OF THIS PAGE
$url = 'http://www.quotegold.com/';

// OTHER SOURCES MIGHT INCLUDE KITCO, YAHOO OR GOOGLE OR THIS:
// $url = 'http://www.goldprice.org/gold-prices/1003-Gold-Coins/1005-GoldMoney.htm';

// GET THE WEB PAGE OR FAIL
if (!$htm = my_curl($url,3,TRUE)) die();

// ISOLATE THE BODY OF THE HTML STRING
$arr = explode('<body', strtolower($htm));
$bod = $arr[1];

// ISOLATE THE PRICE OF GOLD
$arr = explode('style17', $bod);
$arr = explode('</span>', $arr[1]);
$str = preg_replace('/[^0-9\.]/', '', $arr[0]);
echo $str;

// COMMA SEPARATED VALUES
echo ',';

// ISOLATE THE ISO8601 DATETIME OF THE PRICE QUOTE
$arr = explode('style16', $bod);
$arr = explode('</span>', $arr[1]);
$str = str_replace('gold quote updated', '', $arr[0]);
$str = preg_replace('/[^0-9a-z :\-\.]/', '', $str);
$dat = date('c', strtotime($str));
echo $dat;

// END OF JOB
die();




// ACTIVATE THIS TO SEE THE CONTENTS OF THE WEB SITE
// echo "<pre>" . htmlentities($htm);




// A FUNCTION TO READ THE FOREIGN WEB PAGE
function my_curl($url, $timeout=2, $error_report=FALSE)
{
    $curl = curl_init();

    // HEADERS FROM FIREFOX - APPEARS TO BE A BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // browsers keep this blank.

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt($curl, CURLOPT_URL,            $url);
    curl_setopt($curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6');
    curl_setopt($curl, CURLOPT_HTTPHEADER,     $header);
    curl_setopt($curl, CURLOPT_REFERER,        'http://www.google.com');
    curl_setopt($curl, CURLOPT_ENCODING,       'gzip,deflate');
    curl_setopt($curl, CURLOPT_AUTOREFERER,    TRUE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($curl, CURLOPT_TIMEOUT,        $timeout);

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);
    curl_close($curl);

    // ON FAILURE
    if (!$htm)
    {
        // PROCESS ERRORS HERE
        if ($error_report)
        {
            echo "ERROR: CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        return FALSE;
    }

    // ON SUCCESS
    return $htm;
}

Open in new window

0
 

Author Comment

by:egoselfaxis
ID: 33577130
Thanks Ray!  Your script works beautifully.

- Yvan
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33577344
Thanks for the points.  The strategy of "scraping" a web page is a little bit brittle - a change by the author of the page can break your scrape script.  So it is fairly important to check for errors and report them in a timely way.  You might consider sending yourself an email message if the script makes an error or reports data with a timestamp that is too old.  Just a thought.  
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now