Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Retrieving the current gold price (CGP) using PHP

Posted on 2010-09-01
5
Medium Priority
?
2,591 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 111

Expert Comment

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

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 111

Accepted Solution

by:
Ray Paseur earned 2000 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 111

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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

916 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