JSON, XML, and APIs

JSON

JSON, viagra or “Javascript Object Notation” is a text format that was designed to send data in¬†Javascript ¬†code. Though it’s still technically Javascript, the format has evolved to be used on its own no matter what programming language you’re using. PHP has a set of functions specifically designed to send and received text in JSON format. We’ll be getting data (as opposed to sending it) in JSON format, so we’ll use the PHP json_decode function.

Objects in JSON consist of name/value pairs. An object is enclosed in { } (curly brackets). Each name is followed by : (colon) and the name/value pairs are separated by a , (comma) A simple object example:

{
"name":"Grand Central Terminal",
"location": "87 E 42nd St"
}

Arrays are enclosed in [ ] (square brackets) with a , (comma) separating the elements. An array of objects looks like:

[
{
"name":"Grand Central Terminal",
"location": "87 E 42nd St"
},
{
"name":"Penn Station",
"location": "1 Penn Plaza"
}
]

Getting data from other sites: Using APIs

API stands for Application Programming Interface. Specifically, we’re talking about Web APIs, also known as Web Services. This is what lets you do something like display your recent tweets on your personal website or allow users to Login using their Google account. APIs allow you to use a particular site’s services without leaving your own site. To do that, you have to request data from the site in the way that they want you to. Tons of services out there offer APIs to developers. Check out Foursquare, Google, Sunlight Foundation, and OpenWeatherMap

Simple JSON example using OpenWeatherMap

XML

Like JSON, XML is a text format used to pass data back and forth. It will look familiar, because it uses tags, like HTML does. In fact, HTML is a type of XML. PHP has tools to parse XML, such as the SimpleXML set of classes.

Simple XML example using Google Geocoding API

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>