Solved

Retrieving the current gold price (CGP) using PHP

Posted on 2010-09-01
5
2,244 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 109

Expert Comment

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

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 109

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 109

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

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

832 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