PHP script which convert any currency using free API

PHP tutorials

Learn how to convert any currency using a free API in PHP with this step-by-step tutorial. This tutorial shows you how to use the ExchangeRate-API service to convert any amount of one currency to another currency. You will learn how to make API requests in PHP and how to handle the API response. By the end of this tutorial, you will have a working PHP script that can convert any currency. This tutorial is suitable for beginners PHP developers who want to learn how to use APIs in their projects.

This script converts 100 units of the base currency (USD in this example) to the target currency (EUR in this example) using the ExchangeRate-API (https://www.exchangerate-api.com/). You will need to sign up for a free API key in order to use this service. Simply replace your_api_key with your API key in the script above.

You can easily modify this script to convert any currency and any amount by changing the values of the $base, $to, and $amount variables.

<?php

// Set the base currency and the currency to convert to
$base = 'USD';
$to = 'EUR';

// Set the API endpoint and your API key
$endpoint = 'https://api.exchangerate-api.com/v4/latest/';
$key = 'your_api_key';

// Make the API request
$ch = curl_init(); // Initialize a new cURL session
curl_setopt($ch, CURLOPT_URL, "$endpoint$base"); // Set the URL to send the request to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set cURL to return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-Key: $key")); // Set the API key in the request header
$response = curl_exec($ch); // Send the request and store the response
curl_close($ch); // Close the cURL session

// Decode the response and get the exchange rate
$response = json_decode($response, true); // Decode the JSON response into an associative array
$rate = $response['rates'][$to]; // Get the exchange rate from the response

// Convert the amount
$amount = 100; // Set the amount to convert
$converted = $amount * $rate; // Calculate the converted amount

// Print the result
echo "$amount $base is equal to $converted $to"; // Print the result

?>

 

Was this helpful?

1 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *