How can I determine the currency code for the IP address location using PHP?

To determine the currency code for an IP address using IP2Location.io in PHP, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed PHP and we won't cover that here. You will also need a paid subscription to the Plus plan or higher. Subscribe now!
  2. Save the below code into a file called test.php on your computer.
    PHP
    
    $ch = curl_init();
    $ip = '8.8.8.8';
    $key = 'YOUR_API_KEY';
    curl_setopt($ch, CURLOPT_URL, 'https://api.ip2location.io/?' . http_build_query([
    	'ip' => $ip,
    	'key' => $key,
    	'format'  => 'json',
    ]));
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_errno > 0) {
    	echo 'ERROR: ' . $curl_error . PHP_EOL;
    }
    else {
    	$myobj = json_decode((string) $response, true);
    
    	if ($myobj !== null) {
    		if (isset($myobj['error'])) {
    			echo 'ERROR: ' . $myobj['error']['error_message'] . PHP_EOL;
    		}
    		else if (isset($myobj['country'])) {
    			echo 'The currency code for IP ' . $ip . ' is ' . $myobj['country']['currency']['code'] . '.' . PHP_EOL;
    		}
    		else {
    			echo 'ERROR: The currency code field requires a paid subscription to the Plus plan or higher.' . PHP_EOL;
    		}
    	}
    	else {
    		echo 'ERROR: Invalid JSON in response.' . PHP_EOL;
    	}
    }
    			
  3. In the command line, run the below command.
    Bash
    
    php test.php
    			

This script will output the currency code of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free