Postcode Anywhere API: PHP Class

The PHP Class

This is my php class for postcode anywhere. You must have a valid license key and account code. This code is for a postcode anywhere php address lookup using a postcode.

This PHP Postcode Anywhere code was adopted by Postcode Anywherethe for their Postcode Anywhere PHP code examples on their examples pages.

There are three stages:

1. Enter Postcode. Display the postcode input to the user (usually as part of a form for registering, checkout, signup etc). User enters postcode and submits the form.

2. Get addresses. An array of matching addresses from postcode anywhere are returned via getAddressesByPostcode(). This array is looped through and displayed as a dropdown list of addresses – the user chooses their address…

3. Choose Address. The chosen address_id is then sent to postcode anywhere to get the full details for that addresses, this is returned through getAddressByID().

[code language=”php”]<?php
/**
*
* class.postcodeanywhere.php
*
* stuart sillitoe 2011
*
*
*
**/

class PostcodeAnywhere
{

var $account_code;
var $license_key;

var $postcode; // the postcode entered by the user
var $data; // holds address data
var $address_id; // the id of the selected address

function PostcodeAnywhere($account_code, $license_key)
{
$this—>account_code = $account_code;
$this->license_key = $license_key;
}

function getAddressesByPostcode($postcode)
{
$this->setPostcode($postcode);
$url = "http://services.postcodeanywhere.co.uk/xml.aspx?";
$url .= "account_code=" .urlencode($this->account_code);
$url .= "&license_code=" .urlencode($this->license_key);
$url .= "&action=lookup";
$url .= "&type=by_postcode";
$url .= "&postcode=" .urlencode($this->postcode);

$file = simplexml_load_file($url);
if ( !empty($file->Data) )
{
foreach ($file->Data->Item as $item)
{
$this->data[] = array(‘id’=>$item->attributes()->id, ‘description’=>$item->attributes()->description);
}
}
}

function getAddressByID($address_id)
{
$this->setAddressID($address_id);
$sURL = "http://services.postcodeanywhere.co.uk/xml.aspx?";
$sURL .= "account_code=" .urlencode($this->account_code);
$sURL .= "&license_code=" .urlencode($this->license_key);
$sURL .= "&action=fetch";
$sURL .= "&style=simple";
$sURL .= "&id=" . $this->address_id;
$this->data = $this->prepareData($sURL);
}

function prepareData($url)
{
$data = simplexml_load_file($url);
foreach ($data->Schema->Field as $field)
{
$k = (string) $field->attributes()->Name;
$v = (string) $data->Data->Item->attributes()->$k;
$out[$k] = $v;
}
return $out;
}

// get any data
function hasData()
{
if ( !empty($this->data) )
{
return $this->data;
}
return false;
}

// set postcode
function setPostcode($postcode)
{
$this->postcode = strip_tags(trim($postcode));
}
// get postcode
function getPostcode()
{
return $this->postcode;
}

// set address id
function setAddressID($address_id)
{
$this->address_id = (float) $address_id;
}
// get address id
function getAddressID()
{
return $this->address_id;
}

// get address
function getSelectedAddress()
{
if ( $this->hasData() && !empty($this->address_id) )
{
return $this->data;
}
}

}
?>[/code]

The HTML that i use in my form

The following HTML is simply the postcode input and a div that will be used to load in the response. jQuery is used to fetch the content.

[code language=”html”]
<div class="paWrap" id="registerPaWrap" style="clear:left;background:#ddd;padding:10px;margin:0 -10px 10px -10px;overflow:hidden;">

<label for="postcode" class="required"><?php echo TextLabelTranslation::getText(‘form:label:postcode’, $_SESSION[‘CW’][‘id’]); ?></label>
<input type="text" name="postcode" id="postcode" value="<?php echo $this->postcode; ?>" style="width:50px;margin-right:10px;" />
<input type="button" class="button colour" id="addressLookup" value="Find Address" onclick="$(‘#paChooseAddress’).hide();$(‘#registerPaWrap_Addresses’).html(loading);$.post(‘/p/pa.lookup.php’, {postcode: $(‘#postcode’).val()}, function(data){ $(‘#registerPaWrap_Addresses’).html(data); });" />
<br/>

<div id="registerPaWrap_Addresses" class="clearBoth">
</div>

</div>
[/code]

…and the following code in in /p/pa.lookup.php

[code language=”php”]
<?php
require_once($_SERVER[‘DOCUMENT_ROOT’] .’/inc/loader.php’);

// create a new postcodeAnywhere object
$pa = new PostcodeAnywhere(PA_ACCOUNTCODE, PA_LICENSEKEY);

// user has chosen an address…
if (isset($_POST[‘address_id’]))

$pa->getAddressByID($_POST[‘address_id’]);
if ( $pa->hasData() )
{
$address = $pa->getSelectedAddress();
echo json_encode($address);
}
else
{
?><p class="message error">Error: Could not fetch address.</p><?php
}
}
// user has entered a postcode…
else if ( !empty($_POST[‘postcode’]) )
{
$pa->getAddressesByPostcode($_POST[‘postcode’]);
if ( $pa->hasData() )
{
?>
<div id="paChooseAddress">
<label for="address_id">Choose Address</label>
<select name="address_id" id="address_id" style="margin-right:10px;">
<?php
foreach ($pa->data as $address)
{
echo ‘<option value="’ .$address[‘id’] .’">’ .trim($address[‘description’]) .'</option>’;
}
?>
</select>
<input type="button" class="button colour" name="selectAddress" id="selectAddress" value="Select Address" onclick="$.post(‘/p/pa.lookup.php’, {address_id: $(‘#address_id’).val()}, function(data)
{
d = $.parseJSON(data);
$(‘#company_name’).val(d.organisation_name);
$(‘#department’).val(d.department_name);
if ( d.line3 != ” )
{
$(‘#address_1’).val(d.line1 + ‘, ‘ + d.line2);
d.line4 != ” ? $(‘#address_2’).val(d.line3 + ‘, ‘ + d.line4) : $(‘#address_2’).val(d.line3);
}
else
{
$(‘#address_1’).val(d.line1);
$(‘#address_2’).val(d.line2);
}
$(‘#town’).val(d.post_town);
$(‘#county’).val(d.county);
});$(‘#doneWithAddresses’).fadeIn(‘slow’);" />
<input type="button" class="button colour" id="doneWithAddresses" value="Ok" style="margin-left:10px;display:none;" onclick="$(‘#paChooseAddress’).hide();$(this).fadeOut(‘slow’);" />
</div>
<?php
}
else
{
?><p class="message error">Error: No results were found for <?php echo $pa->postcode; ?>. Please try again.</p><?ph
}
}
?>[/code]

The javascript above may or may not be neccessary for you. i need it to load the response data into my address form.

The Postcode Anywhere version is below, for clarity and completeness.

[code language=”php”]
class PostcodeAnywhere_Interactive_FindByPostcode_v1_00
{

//Credit: Thanks to Stuart Sillitoe (<a href="http://stu.so/me">http://stu.so/me</a>) for the original PHP that these samples are based on.

private $Key; //The key to use to authenticate to the service.
private $Postcode; //The postcode to search with find.
private $UserName; //The username associated with the Royal Mail license (not required for click licenses).
private $Data; //Holds the results of the query

function PostcodeAnywhere_Interactive_FindByPostcode_v1_00($Key, $Postcode, $UserName)
{
$this->Key = $Key;
$this->Postcode = $Postcode;
$this->UserName = $UserName;
}

function MakeRequest()
{
$url = "http://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/FindByPostcode/v1.00/xmla.ws?";
$url .= "&Key=" . urlencode($this->Key);
$url .= "&Postcode=" . urlencode($this->Postcode);
$url .= "&UserName=" . urlencode($this->UserName);

//Make the request to Postcode Anywhere and parse the XML returned
$file = simplexml_load_file($url);

//Check for an error, if there is one then throw an exception
if ($file->Columns->Column->attributes()->Name == "Error")
{
throw new Exception("[ID] " . $file->Rows->Row->attributes()->Error . " [DESCRIPTION] " . $file->Rows->Row->attributes()->Description . " [CAUSE] " . $file->Rows->Row->attributes()->Cause . " [RESOLUTION] " . $file->Rows->Row->attributes()->Resolution);
}

//Copy the data
if ( !empty($file->Rows) )
{
foreach ($file->Rows->Row as $item)
{
$this->Data[] = array(‘Id’=>$item->attributes()->Id,’StreetAddress’=>$item->attributes()->StreetAddress,’Place’=>$item->attributes()->Place);
}
}
}

function HasData()
{
if ( !empty($this->Data) )
{
return $this->Data;
}
return false;
}

}

//Example usage
//————-
//$pa = new PostcodeAnywhere_Interactive_FindByPostcode_v1_00 ("AA11-AA11-AA11-AA11","WR2 6NJ","David");
//$pa->MakeRequest();
//if ($pa->HasData())
//{
// $data = $pa->HasData();
// foreach ($data as $item)
// {
// echo $item["Id"] . "<br/>";
// echo $item["StreetAddress"] . "<br/>";
// echo $item["Place"] . "<br/>";
// }
//}
[/code]




No Comments


You can leave the first : )



Leave a Reply

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