You can use the Yahoo YQL, through the Query: select Rate from yahoo.finance.xchange where pair in ("USDBRL")
, for example, the USDBRL
must be set by what you want, this case will be returned 3.1141
, it seems to be updated in real time.
You need to get the answer as follows:
http://query.yahooapis.com/v1/public/yql?
q=select%20Rate%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDBRL%22)
&format=json
&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
Basically use:
function converterMoeda(string $de, string $para){
$parametros = [
'q' => 'select Rate from yahoo.finance.xchange where pair = "'.$de.$para.'"',
'env' => 'store://datatables.org/alltableswithkeys',
'format' => 'json'
];
$parametros = http_build_query($parametros, '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('http://query.yahooapis.com/v1/public/yql?'.$parametros);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FAILONERROR => 1
]);
if($resultado = curl_exec($ch)){
$resultado = json_decode($resultado, true);
return $resultado['query']['results']['rate']['Rate'];
}
return false;
}
if($resultado = converterMoeda('USD', 'BRL')){
echo $resultado;
}
At this point the result is 3,1141, but logically it will change. It supports multiple currencies, including Bitcoin, you can use BTCBRL
and will return, now, 3982.2249
.
Just updating, API facinha: https://docs.awesomeapi.com.br/api-de-moedas
– Herbert Smith