Solved

Retrieving the current gold price (CGP) using PHP

Posted on 2010-09-01
5
2,453 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
5 Comments
 
LVL 110

Expert Comment

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

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 110

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 110

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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

626 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