Solved

Retrieving the current gold price (CGP) using PHP

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
echo button 13 48
confirm popup before record delete takes place 87 25
Strip leading 0 from a var 3 14
How to fetch your row in php 14 13
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
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…
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…

743 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

13 Experts available now in Live!

Get 1:1 Help Now