Some way to get the price of the dollar

6

Do you know of any api or other php way to get the price of the dollar? I just need the price of the dollar for the real thing. I've tried these two api's, but the two are off the air. link link

Thank you!

    
asked by anonymous 06.03.2017 / 15:30

4 answers

5

You can use Yahoo YQL through Query: select Rate from yahoo.finance.xchange where pair in ("USDBRL") ", for example, the USDBRL must be defined 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 in the following way:

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 it will now return 3982.2249 .

    
06.03.2017 / 16:33
5

You can use the webservice of the Central Bank:

link

I think I'm more reliable and because it's a state service, there's no risk of a developer taking it off anytime.

Here is an example of how to implement:

<?php

// Mostra erros
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('default_socket_timeout', 300);

$debug = true;
$result = null;
$error = null;
$exception = null;
$xml = null;


// Definição da localização do arquivo WSDL
$wsdl = 'https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl';

// Soapclient PHP 5.0 ou Superior ( SOAP 1.1 e SOAP 1.2 )
$client = new Soapclient($wsdl, array('trace' => 1, 'exceptions' => true));



$xml =' <?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://publico.ws.casosdeuso.sgs.pec.bcb.gov.br" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:getUltimoValorVO>
<in xsi:type="xsd:long">'. '206'.'</in>
</ns1:getUltimoValorVO>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>';
// Chamada do método SOAP
try {
    //$serie = 206;
    $result = $client->getUltimoValorVO($xml, $serie);

    if (is_object($result)) {
        if (!$result->getUltimoValorVOResult) {
            $error = $result->getUltimoValorVOError;
        }
    }

    if (is_soap_fault($result)) {
        trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
    }

} catch (Exception $e) {
    $exception = $e->getMessage();
}

if ($debug) {
    echo '<h2>Request Headers</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastRequestHeaders()) . '</pre>';

    echo '<h2>Response Headers</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastResponseHeaders()) . '</pre>';

    echo '<h2>Request</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastRequest()) . '</pre>';

    echo '<h2>Response</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastResponse()) . '</pre>';

    echo '<h2>Debug</h2>';
    echo '<pre>' . var_dump($result) . '</pre>';

    echo '<h2>Exception</h2>';
    echo '<pre>' . var_dump($exception) . '</pre>';

    echo '<h2>Error</h2>';
    echo '<pre>' . $error . '</pre>';
}

?>
    
06.03.2017 / 16:03
5

Fixer.io

Fixer.io which is a free and simple-to-use API.

By giving a GET at link you have a JSON as a result:

{"base":"USD","date":"2017-03-03","rates":{"BRL":3.1311}}

The database is from the European Central Bank and is updated once a day.

currencylayer

Another option is Currency Layer . It has free and paid plans, no matter what registry you need to use. The free is limited to 1000 accesses per month and the values are updated every hour.

Other plans here: link

    
06.03.2017 / 15:38
2

Here's another example for using BACEN's webservice.

Just instantiate the BACEN class and use the getUltimoValorXML function for the last quote or getValor for quotation on a specific date.

Remembering that the code for the dollar is 1.

class SOAP extends SOAPClient {

    private static $bacen_instance;

    private function SOAP($bacen_url) {
        return parent::__construct($bacen_url, array('soap_version' => SOAP_1_1));
    }

    public static function getInstance($bacen_dados) {
        if (empty(self::$bacen_instance))
            self::$bacen_instance = new SOAP($bacen_dados);

        return self::$bacen_instance;
    }

    public function call($teste, $bacen_configuracoes) {
        return parent::__soapCall($teste, $bacen_configuracoes);
    }

}


class BACEN {
    private $bacen_url = "https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl";

    /**
     *Função para acessar soap
     * @access public
     * @param array contendo os itens necessários para o retorno do webservice
     * @return objeto XML 
     */
    public function soap($teste, $bacen_conf){
        $bacen_cliente = SOAP::getInstance($this->bacen_url);

        $bacen_resultado = $bacen_cliente->call($teste, $bacen_conf);
        return ($bacen_resultado);        
    }   

    /**
     *

     */
    public function getUltimoValorXML($bacen_cod_moeda) {
        $bacen_conf[0] = 'getUltimoValorXML';
        $bacen_conf[1] = array('in0' => $bacen_cod_moeda);
        return $this->soap($bacen_conf);
    }

       /**
     *

     */
    public function getValor($bacen_cod_moeda, $databr) {
        $bacen_conf['in0'] = $bacen_cod_moeda;
        $bacen_conf['in1'] = $databr;
        $retorno = $this->soap('getValor', $bacen_conf);
        return $retorno;
    }
}
    
06.03.2017 / 16:16