Stuneris
Stuneris

Reputation: 77

How to get info from YQL currency?

I tried alot of scripts from internet, but anyone works for me, so mabie you can help me, I don't know how to create PHP code to get rates of EUR to DKK. I need code something like this:

$dkk_rate = ???
$euros = 100;
$krones = $euros * $dkk_rate;

Upvotes: 1

Views: 329

Answers (2)

Nikos
Nikos

Reputation: 3297

One simple approach is to download the latest rate from Yahoo Finance. For example:

<?php
  $x = file_get_contents("http://download.finance.yahoo.com/d/quotes.csv?s=EURDKK=X&f=sl1d1t1ba&e=.json");
  $x=explode(",",$x);
  echo "FX rate of EURDKK is ".$x[1]." at ".$x[2];
?>

You could wrap it up in a function as follows:

<?php
  function convertCurrency($from,$to,$amount) {
     $x = file_get_contents("http://download.finance.yahoo.com/d/quotes.csv?s=$from$to=X&f=sl1d1t1ba&e=.json");
     $x=explode(",",$x);
     echo "$amount of $from is equal to ".($amount*$x[1])." $to";
  }

  convertCurrency("EUR","DKK",100);
?>

which will output: 100 of EUR is equal to 745.33 DKK

Hope this helps.

Upvotes: 1

Nilesh Dharmik
Nilesh Dharmik

Reputation: 359

From PHP Snippets

function currency($from_Currency,$to_Currency,$amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);
    $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('"', $rawdata);
    $data = explode(' ', $data['3']);
    $var = $data['0'];
    return round($var,2);
}

You dont necessarily need cURL for that though. file_get_contents should do too if the allow_furl_open is enabled:

$result = file_get_contents(
    'http://www.google.com/ig/calculator?hl=en&q=100EUR=?USD'
);

This would return something like

{lhs: "100 Euros",rhs: "129.18 U.S. dollars",error: "",icc: true}

Upvotes: 0

Related Questions