Last active
August 31, 2020 03:46
-
-
Save trvswgnr/49903d3c2f35e383dcb6a5d304c0d80b to your computer and use it in GitHub Desktop.
PHP - Get county name by zip code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php/** | |
* Get county name by zip code | |
* | |
* @param string|int $zip Zip code to lookup. | |
* @return string $countyname Formatted county name. | |
*/ | |
function get_county_by_zip( $zip ) { | |
// google maps api. | |
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $zip . '&key=AIzaSyC3TG7THSJjHbzDpYyQagJvWP-Inu6i33s'; | |
$response = json_decode( file_get_contents( $url ), true ); | |
$countyname = ! empty( $response['results'][0]['address_components'][2]['long_name'] ) ? $response['results'][0]['address_components'][2]['long_name'] : ''; | |
$type = ! empty( $response['results'][0]['address_components'][2]['types'][0] ) ? $response['results'][0]['address_components'][2]['types'][0] : ''; | |
// zip-codes.com api fallback. | |
if ( 'administrative_area_level_2' !== $type ) { | |
$url = 'https://api.zip-codes.com/ZipCodesAPI.svc/1.0/QuickGetZipCodeDetails/' . $zip . '?key=VDVU3356B446IYE6FQON'; | |
$response = json_decode( file_get_contents( $url ), true ); | |
$countyname = ! empty( $response['County'] ) ? $response['County'] : ''; | |
} | |
// format county name to match database counties. | |
$countyname = str_replace( 'Saint', 'St.', str_replace( ' County', '', ucwords( strtolower( $countyname ) ) ) ); | |
return $countyname; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment