Hello World - PHP ExampleΒΆ

Here is a simple example in PHP that will show you how to:

  • get an API token,
  • search for official information for a given address,
  • obtain map images, and
  • create a formatted HTML page with information about the officials and a map of their districts
<?php
// Some constants that we will use:
$username = 'YOUR_USERNAME_HERE';
$password = 'YOUR_PASSWORD_HERE';
$search_loc = '1200+Callowhill+St';

// Function to do our API calls (returns object made from JSON)
function get_response($url, $postfields=''){
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, True);
    if($postfields !== ''):
        curl_setopt ($ch, CURLOPT_POST, True);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
    endif;
    $json = curl_exec($ch);
    curl_close($ch);
    return json_decode($json);
}

// Obtain a token:
$response = get_response('http://cicero.azavea.com/v3.1/token/new.json', "username=$username&password=$password");

// Check to see if the token was obtained okay:
if($response->success != True):
    exit('Could not obtain token.');
endif;

// The token and user obtained are used for other API calls:
$token = $response->token;
$user = $response->user;

// Get an official query response
$query_string = "search_loc=$search_loc&token=$token&user=$user&format=json";
$official_response = get_response("http://cicero.azavea.com/v3.1/official?$query_string");

if(count($official_response->response->results->candidates) == 0):
    die('No location found for the given address.');
endif;

// Print information for each official:
foreach($official_response->response->results->candidates[0]->officials as $o):
?>
    <h1><?php echo $o->first_name?> <?php echo $o->last_name?></h1>
    <h2><?php echo $o->office->title?></h2>
    <?php foreach($o->addresses as $a):?>
        <p>
        <?php echo $a->address_1?><br/>
        <?php echo $a->address_2?><br/>
        <?php echo $a->city?>
        <?php echo $a->county?>
        <?php echo $a->state?>
        <?php echo $a->postal_code?>
        </p>
    <?php endforeach;
    // show a map:
    $district_id = $o->office->district->id; // get district ID to use for the map
    $map_url = "http://cicero.azavea.com/v3.1/map/$district_id?token=$token&user=$user&include_image_data&format=json";
    $map_response = get_response($map_url);
    if(count($map_response->response->results->maps) > 0):
        $src = $map_response->response->results->maps[0]->img_src
        ?>
        <img alt="Map" src="<? echo $src?>">
        <?php
    endif;
?><hr/><?php
endforeach;
?>

Previous topic

Hello World - ASP.NET / C# Example

Next topic

Hello World - jQuery Example