Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store
Related Articles

Geocoding with PHP and the Google Maps API

Performing a Geocoder Request

When you perform a geocoder request, you can specify which output type to use. The available options are JSON, XML, KML and CSV. In this article we will be requesting and handling XML data.

Note: KML (which stands for Keyhole Markup Data) is an XML format that was developed for use with Google Earth (formerly called Keyhole). The KML and XML output from the geocoder are identical; however the HTTP mime type that is sent differs for the two types.

Although JSON data is typically used within JavaScript code, we could also easily use this data instead of the XML response. To turn the data into a PHP array you could use the json_decode() function (available since PHP 5.2.0). We will be using SimpleXML in this article to read geocoder data, but to use JSON instead would be a trivial change.

To perform a geocoder request, a HTTP get request is sent to There are three URI parameters that must be specified in this request:

  • q The address or location that you want to geocoded.
  • key This is the Google Maps API key that you created earlier in this article.
  • output This the output format for the response (as discussed above). The values that can be used are json, xml, kml or csv.

For example, if you wanted to find the coordinates of The White House (located at 1600 Pennsylvania Avenue, Washington, DC), you would request the following URL:

Listing 1 Querying the geocoder for a the address of the White House in XML format (listing-1.txt)
Note: Remember to substitute your own API key in the request URL.

The precise address string you send in the query is not critical it simply needs enough data in it to identify the location you're after (that is, it should not be ambiguous).

In This Article

Additional Files