Skip to content

Instantly share code, notes, and snippets.

@jotapepinheiro
Created April 6, 2012 20:53
Show Gist options
  • Save jotapepinheiro/2322847 to your computer and use it in GitHub Desktop.
Save jotapepinheiro/2322847 to your computer and use it in GitHub Desktop.
Conversão de Moedas
<?php
$preco=Convert('USD', 'BRL','535,93');
if($preco!=false){
echo $preco;
}
else{echo "conversão não possível";}
/**
* [Converte Moedas]
* @example http://www.google.com/finance/converter
* @param [string] $from [description]
* @param [string] $to [description]
* @param [string] $preco [description]
*/
function Convert($from, $to, $preco)
{ $url = "http://www.google.com/finance/converter?a=$preco&from=$from&to=$to";
$data = getPage($url);
if(empty($data))
return false;
$dom = new DOMDocument();
@$dom->loadHTML($data);
$return = @$dom->getElementById('currency_converter_result')
->getElementsByTagName('span')
->item(0)
->firstChild
->wholeText;
$return = (float)$return;
if($return == 0 )
return false;
return number_format($return,2);
}
/**
* [getPage description]
* @param [type] $url [description]
* @return [type] [description]
*/
function getPage($url)
{ if(ini_get('allow_url_fopen') != 1) {
@ini_set('allow_url_fopen', '1');
}
if(ini_get('allow_url_fopen') != 1) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$data = curl_exec($ch);
curl_close($ch);
}
else {
$data = file_get_contents($url);
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment