John Davidson

php - Accessing exchange rates converted into CAD from USD isn't working

0 comments
Message:


I'm not sure why the test program below isn't getting the response from the API. Here is the document for the API. It's working absolutely fine on the provider's playground. Running the test program below doesn't do anything at all.


<?php
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.apilayer.com/exchangerates_data/convert?to=CAD&from=USD&amount=1",
CURLOPT_HTTPHEADER => array(
"Content-Type: text/plain",
"apikey: av5CJRrOA2Rclj4fai3UZF5NT7F9HmPr"
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
?>


My Answer:
To access exchange rates converted into CAD from USD in PHP, you can use an API provided by a financial data provider such as Open Exchange Rates or CurrencyLayer. Here is an example using the Open Exchange Rates API:

php

$appId = 'YOUR_APP_ID'; // Your Open Exchange Rates API key
$baseCurrency = 'USD';
$targetCurrency = 'CAD';

$url = "https://open.er-api.com/v6/latest/{$baseCurrency}?app_id={$appId}";

$response = file_get_contents($url);
$data = json_decode($response, true);

if ($data && isset($data['rates'][$targetCurrency])) {
$exchangeRate = $data['rates'][$targetCurrency];
echo "1 {$baseCurrency} is equal to {$exchangeRate} {$targetCurrency}";
} else {
echo "Failed to retrieve exchange rate data";
}


Replace `'YOUR_APP_ID'` with your actual Open Exchange Rates API key. This code will fetch the latest exchange rates from USD to CAD and display the conversion rate. You can then use this exchange rate to convert any amount from USD to CAD in your PHP application.

Rate this post

3 of 5 based on 8051 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us