PHP code example of alexpechkarev / postcode-anywhere
1. Go to this page and download the library: Download alexpechkarev/postcode-anywhere library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
alexpechkarev / postcode-anywhere example snippets
$param = [
'action' => 'Web Service',
'parameters' => 'array of parameters for Web Service called'
];
$param = [
'find' => 'FindByPostcode', // perform 'find' action calling 'FindByPostcode' web service
'param' => ['postcode'=>'SW1A 1AA', 'endpoint'=>'json'] // parameters for web service called
];
namespace App\Services;
class Loqate
{
/**
* @var \Illuminate\Support\Collection
*/
public $addresses;
/**
* Retrieve an address by it's postcode.
*
* @param string $postcode
*
* @return array
*/
public function __construct($postcode)
{
// Build an addresses collection
$addresses = collect();
// Step 1: Search by postcode to get Loqate's internal ID.
$param = [
'find' => 'FindByPostcode',
'param' => [
'postcode' => $postcode,
'endpoint' => 'json',
],
];
// JSON Decode the returned response into an array
$findResponse = json_decode(\PA::getResponse($param), true);
// Loop through the returned array
foreach ($findResponse as $findItem) {
if (array_key_exists('Id', $findItem)) {
// Step 2: Retrieve the full address by it's ID.
$param = [
'retrieve' => 'RetrieveById',
'param' => [
'id' => $findItem['Id'],
],
];
// JSON Decode the returned response into an array
$retrieveResponse = json_decode(\PA::getResponse($param), true);
// Loop through the returned array
foreach ($retrieveResponse as $item) {
// Push to the collection
$addresses->push($item);
}
}
}
// Convert all keys to snake case
$addresses = $addresses->map(function ($value, $key) {
return collect($value)->keyBy(function ($value, $key) {
return snake_case($key);
});
});
$this->addresses = $addresses;
}
/**
* Retrieve the Addresses Property as an array.
*
* @return array
*/
public function toArray()
{
return $this->addresses->toArray();
}
/**
* Retrieve the Addresses Property unmodified.
*
* @return \Illuminate\Support\Collection
*/
public function get()
{
return $this->addresses;
}
}
$postcode = 'WR5 3DA';
$addresses = new App\Services\Loqate($postcode);
return $addresses->toArray();