August 2011 Archives

Accessing the CTA's API with PHP

| | | |

Last month the City of Chicago arranged for a Open Data Hackaton in which a collection of programmers gathered together to develop and write programs that utilize a new resource, open access to city information.

For my part, I spent the data writing a PHP class file that wraps around the Chicago Transit Authority's web-based application programming interface, enabling access to CTA bus, rail and service information for PHP driven applications. As I've noted in the README file, "this class brings all three APIs together into one object with related methods."

The following in a quick rundown of how to incorporate this new class file into a working PHP application.

The first step is to download the class.cta.php file from GitHub and save it in a location that the PHP application has read access.

The next step is to include the file using the include (or similar require) function in the PHP application itself:

// Load the class file in our current directory
include_once( 'class.cta.php' );

Once the class file has been loaded, the next step is to instantiate the class:

$transit = new CTA ( 

Notice that initialization of transit includes providing two API keys. API Keys can be requested from the CTA. For an API Key for Train Tracker, use the Train Tracker API Application form. For Bus Tracker, first sign into Bus Tracker, then request an Developer Key under "My Account".1

If no valid API keys are provided the only methods that will return valid information are the Customer Alert functions for system status information. Specificity the two functions statusRoutes and statusAlerts. This is because the Customer Alert API does not require an API key for access.

To invoke a method simply use the object and related function, providing any additional information as parameters, if required. For example, to get information about all of the bus stops the east-bound route 81 bus makes:

// Get an array result of all stops for an east-bound 81 bus.
$EastBoundStops = $transit->busGetStops( '81', 'East Bound' ));

All methods return an array which can be accessed to retrieve desired information. PHP's print_r or var_dump functions provide insight into all information returned by a specific function:

echo '<pre>';
print_r( $transit->busGetStops( '81', 'East Bound' ));
echo '</pre>';

The output will look something akin to this:

SimpleXMLElement Object
	    [stop] => Array
	            [0] => SimpleXMLElement Object
	                    [stpid] => 3751
	                    [stpnm] => 2900 W Lawrence
	                    [lat] => 41.968500785328
	                    [lon] => -87.701137661934
	            [49] => SimpleXMLElement Object
 	                   [stpid] => 3725
	                    [stpnm] => Milwaukee & Higgins
	                    [lat] => 41.969027266773
	                    [lon] => -87.761798501015



In order to generate the following output listing the location of the Lawrence & Kimball stop:

Lawrence & Kimball (Brown Line)
At 41.968405060961 North and -87.713229060173 West

The following PHP code will provide the latitude and longitude of the Kimball stop, which is also a transfer point to the El's Brown Line:

$EastBoundStops = $transit->busGetStops( '81', 'East Bound' );
foreach( $EastBoundStops as $stop ) {

     if ( preg_match( '/kimball/i', $stop->stpnm )) {
          echo $stop->stpnm;
          echo 'At ' .$stop->lat. 'North and ' .$stop->lon. ' West';

Notice that while the list of stops is provided in an array, each element in the array is a SimpleXMLElement object, thus the use of the object syntax for accessing each element.

The train function will allow for the determination of rail information, for example when the next Brown line train will be leaving the Kimball stop. However, while the previous example included a stop id for the route 81 bus at Kimball, the stop id is unique to the route 81 bus and does not translate to the stop id of the Brown line El at Kimball. Therefore, the first step is to locate the relevant GTFS2 data for the Kimball station:

/*	Per the CTA's website, El routes are identified as follows:

	Red = Red Line
	Blue = Blue Line
	Brn = Brown Line
	G = Green Line
	Org = Orange Line
	P = Purple Line
	Pink = Pink Line
	Y = Yellow Line
	Which means our Brown line is 'brn' 
$brownStops = $transit->train( '', '', '', 'brn' );
foreach( $brownStops as $stop ) {

	if ( preg_match( '/kimball/i', $stop->staNm )) {
		echo "$stop->staNm train is destined for $stop->stpDe ";
		echo "Scheduled to arrive/depart at $stop->arrT";

Which provides output similar to the following:

Kimball train is destined for Service toward Loop
Scheduled to arrive/depart at 20110821 17:17:01

One should note that the Brown line stop at Kimball is the northern end point for the Brown line, which means any trains leaving the station will only be bound in one direction, south, toward the Loop. If the string comparison is changed to 'irving' for the Irving Park station, the output changes to something similar, with trains running in both directions:

Irving Park train is destined for Service toward Kimball
Scheduled to arrive/depart at 20110821 17:19:34

Irving Park train is destined for Service toward Kimball
Scheduled to arrive/depart at 20110821 17:23:13

Irving Park train is destined for Service toward Loop 
Scheduled to arrive/depart at 20110821 17:19:44

Irving Park train is destined for Service toward Kimball 
Scheduled to arrive/depart at 20110821 17:32:19 

In Review
class.cta.php is a single PHP class file that provides access to all three CTA APIs for Bus, Train and Service information. The class implement functions for access to all API methods and returns an array of SimpleXMLElement objects that a PHP developer can use to incorporate real-time information about Chicago's public transit system.

Additional information about the CTA's APIs, including terms of use and how to request API Keys, can be found on the CTA's Developer page.

1 Why two different API Keys, one for train and one for bus information? Due to the evolution of the CTA's API interfaces, there are three distinct APIs, one for Bus, Train and Customer Alerts information. As a result there are three distinct URI endpoints and two distinct API keys.

2 The CTA provides its data based on the Google Transit Feed Specification (GTFS) which is becoming a common format for public transportation agencies to publishing schedules and associated geographic information. The CTA generates and distributes, about once a week, an up-to-date zip compressed collection of files that includes basic agency information, route, transfer and stop locations, and other related service information. Note that ids 0-29999 are bus stops, ids 30000-39999 are train stops and 40000-49999 train stations (parent stops).

Chicago's Technology Scene, circa 2011

| | | |

Roughly this time two years ago, I attended an entrepreneur and startup event in D.C. called Social Matchbox which I noted in a subsequent blog post of the same name.

While I know organizations and companies like those exists in many places I have yet to find a loose confederation of those individuals, organizations and companies similar to what I experienced in the Bay Area here in Chicago where I currently reside. I have however found such a network in Washington, DC and it is known as Social Matchbox.

Last year, I asked with all the things going for Chicago, high profile tech companies, top tier universities and a diverse population, "why don't tech people think of Chicago along the lines of a San Francisco, Seattle, New York, Boston or Austin?" Perhaps, I surmised, it was simply "that Midwestern work ethic, if we just work hard; the rewards and recognition will come on their own."

This year, I watched as the Chicago tech community rallied around TechWeek, a "celebration of a new technology epicenter unique among major world cities."

It's a start.

Alas, while I didn't get to attend any TechWeek specific events, someone has to keep an eye on the servers and write code for all these newfangled ideas, I did get a chance to meet up with a few other developers at the Chicago Open Data Hackathon. As a WTTW article wrote:

Chicago's city government has worked on developing its high-tech cred by initiatives such as publishing new city data sets online weekly and refreshing those sets nightly in order to increase the city's transparency ... On July 16, Google Chicago hosted a Chicago Open Data Hack Day. The event gathered 60 engineers, designers, and entrepreneurs to share ideas about using the City's open data to create new products and services."1

In my own participation of the hackathon, I did get a chance to create, what I hope will be, a useful PHP library (more on that later).

It's good to see Chicago get a little more boisterous about its tech creds. But it is also good to see Chicago go about about business as most Chicagoans do, as I did last week. As Orbit's Andy Crestodina notes "in a refreshing way, TechWeek was nothing new. Chicago has been doing this a long time and the tech community is an experienced crowd, many of whom have seen the boom and bust (and more booms and more busts) and lived to tell about it."

There is an end in all this technology means. We build apps to communicate. We open data to map relationships and piece out new meaning. The technology isn't an end unto itself. We work in technology to get something done.

And that's the innovation Chicago can bring to the table, even if it mostly goes unheralded.

1 I don't recall 60 people offhand, I probably would have put the count at around 30-40. But the hackathon was an all-day event and I know some people came and left, so, 60 total for the whole maybe true.

About the Author

Paul is a technologist and all around nice guy for technology oriented organizations and parties. Besides maintaining this blog and website you can follow Paul's particular pontifications on the Life Universe and Everything on Twitter.


Add to Google Reader or Homepage
Add to My AOL

Add to netvibes
Subscribe in Bloglines
Add to Technorati Favorites

Movable Type Pro