PHP code example of wprigollopes / bcb-ptax

1. Go to this page and download the library: Download wprigollopes/bcb-ptax library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wprigollopes / bcb-ptax example snippets


use BcbPtax\PTAX;
use BcbPtax\Currency;

$ptax = new PTAX();
$result = $ptax->get(Currency::USD, new \DateTime('2024-01-15'));

echo $result->buyRate;      // 4.8759 (cotacaoCompra)
echo $result->sellRate;     // 4.8765 (cotacaoVenda)
echo $result->bulletinType; // "Fechamento PTAX"
echo $result->date->format('Y-m-d'); // "2024-01-15"

use BcbPtax\PTAX;
use BcbPtax\Currency;
use GuzzleHttp\Client;

$ptax = new PTAX(
    client: new Client(['timeout' => 10]),
);

$result = $ptax->get(Currency::EUR, new \DateTime('2024-06-20'));

$ptax = new PTAX(locale: 'pt_BR');

// Throws: "Nenhum PTAX de fechamento encontrado para USD em 01-01-2024"
$ptax->get(Currency::USD, new \DateTime('2024-01-01')); // Holiday, no PTAX

use BcbPtax\PTAX;
use BcbPtax\Currency;
use BcbPtax\Exception\ApiException;

$ptax = new PTAX();

try {
    $result = $ptax->get(Currency::USD, new \DateTime('2024-01-15'));
    echo "Buy rate: {$result->buyRate}";
} catch (ApiException $e) {
    // API returned an error, no data for that date, or malformed response
    echo "Error: {$e->getMessage()}";
}

use BcbPtax\PTAX;
use BcbPtax\Currency;

$input = 'USD';
$currency = Currency::tryFrom($input);

if ($currency === null) {
    echo "Unsupported currency: {$input}";
    return;
}

$ptax = new PTAX();
$result = $ptax->get($currency, new \DateTime('2024-01-15'));

new PTAX(
    ClientInterface $client = new Client(), // Custom Guzzle client (optional)
    string $locale = 'en_US',               // 'en_US' or 'pt_BR'
)