Get zipcode from address using Google Maps API and PHP

Many times we are needed to extracting zipcode from address in our project. Using Google Maps API and PHP we can easily get zipcode from address. We had created a simple PHP script for getting zipcode from address.

getZipcode() function accept one parameter ($address), into the $address you need to provide the full address from where you want to get zipcode.

getZipcode() function is given below:

* Author: CodexWorld
* Author URI:
* Function Name: getZipcode()
* $address => Full address.
function getZipcode($address){
//Formatted address
$formattedAddr str_replace(' ','+',$address);
//Send request and receive json data by address
$geocodeFromAddr file_get_contents(''.$formattedAddr.'&sensor=true_or_false'); 
$output1 json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$latitude  $output1->results[0]->geometry->location->lat
$longitude $output1->results[0]->geometry->location->lng;
//Send request and receive json data by latitude longitute
$geocodeFromLatlon file_get_contents(''.$latitude.','.$longitude.'&sensor=true_or_false');
$output2 json_decode($geocodeFromLatlon);
$addressComponents $output2->results[0]->address_components;
$addressComponents as $addrComp){
$addrComp->types[0] == 'postal_code'){
//Return the zipcode
return $addrComp->long_name;


Use getZipcode() function like the following.

$address 'Rashtrapati Bhawan, Raisina Hills, New Delhi';
$zipcode getZipcode($address);
$zipcode $zipcode?$zipcode:'Not found';

To specify a Google API key in your request, include it as the value of a key parameter.

$geocodeFromAddr file_get_contents(''.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey');


  1. Arun Verma Said...
  2. Sagar Said...

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.