Map cities of UK onto postcodes - php

I was wondering if anyone is aware of any PHP scripts which maps a UK City onto a Post Code.
I have found something like this:
case'North West England, England': {
$postcode = 'M1 2NQ';
break;
}
case'North East England, England': {
$postcode = 'NE1 6AD';
break;
}
case'South West England, England': {
$postcode = 'EX1 3AX';
break;
}
But it only covers areas as you can see, rather than cities such as 'Manchester, Edinburgh' etc.
Any input would be greatly appreciated.
Thanks,
AP

You might think of using Google Map API

You can use the ONS Postcode Directory (ONSPD). You'd have to set up a database and import all the data, then build your application round it.

Related

SimpleXML selecting attributes with PHP?

Okay so I've never worked with SimpleXML before and I'm having a few problems
Here's my PHP:
map.api.php
$location = $_SESSION['location'];
$address = $location; // Business Location
$prepAddr = str_replace(' ','+',$address);
$feedUrl="http://nominatim.openstreetmap.org/search?q=". $prepAddr ."&format=xml&addressdetails=1&polygon=1";
$sxml = simplexml_load_file($feedUrl);
foreach($sxml->attributes() as $type){
$lat = $type->place['lat'];
$long = $type->place['lon'];
}
And here's an example of the XML table I'm working from.
<searchresults timestamp="Thu, 28 Jan 16 14:16:34 +0000" attribution="Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright" querystring="M27 6bu, 149 Station road, Swinton, Manchester" polygon="true" exclude_place_ids="65827001" more_url="http://nominatim.openstreetmap.org/search.php?format=xml&exclude_place_ids=65827001&accept-language=en-US,en;q=0.8&polygon=1&addressdetails=1&q=M27+6bu%2C+149+Station+road%2C+Swinton%2C+Manchester">
<place place_id="65827001" osm_type="way" osm_id="32861649" place_rank="26" boundingbox="53.5122168,53.5190893,-2.3402445,-2.3331231" lat="53.5156919" lon="-2.3368185" display_name="Station Road, Newtown, Salford, Greater Manchester, North West England, England, M27 4AE, United Kingdom" class="highway" type="secondary" importance="0.5">
<road>Station Road</road>
<suburb>Newtown</suburb>
<town>Salford</town>
<county>Greater Manchester</county>
<state_district>North West England</state_district>
<state>England</state>
<postcode>M27 4AE</postcode>
<country>United Kingdom</country>
<country_code>gb</country_code>
</place>
</searchresults>
I want to select the "lat" and "lon" attributes from <place>, but when I echo $lat and $long they are empty, why?
When you call attributes as you did above, it's only going to act on the first element, which in your case is the root. You need to call attributes on the element you want the attributes for. Easiest way to do that would be
$sxml->place[0]->attributes()
Does that make sense? Basically you're telling SimpleXML to seek to the element you want to analyze, then returning a new SimpleXML object that represents that element's attributes. See if the docs help
Another option you have is using xpath to return all place elements, then iterating through those and calling attributes() on each element, in the case where you have more than one place.
Okay so I fixed this myself.
Instead of running everything through the foreach loop (as shown below):
foreach($sxml->attributes() as $type){
$lat = $type->place['lat'];
$long = $type->place['lon'];
}
I just directly got the attribute values and stored them in a variable:
$lat = $sxml->place->attributes()->lat;
$long = $sxml->place->attributes()->lon;
This then returned an error/warning: Warning: main() [function.main]: Node no longer exists
By using isset and checking if the value exists first, you can get around this.
if (isset($sxml->place))
{
$lat = $sxml->place->attributes()->lat;
$long = $sxml->place->attributes()->lon;
}

PhP - How do I block every EU country except the UK, and allow all non EU countries?

I want a page to block EU countries except the UK, while allowing all other non-EU countries. By block I mean I want another message, such as "Service Unavailable in your Country" appearing rather than the normal page content. How can this be done?
Note: I do not want to effect google-bot ranking by blocking these non-UK EU countries.
Edit: It's a VAT MOSS thing, nothing sinister.
You can use the geoplugin.net geo API.
//Get user IP address
$ip=$_SERVER['REMOTE_ADDR'];
//Using the API to get information about this IP
$details = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=$ip"));
//Using the geoplugin to get the continent for this IP
$continent=$details->geoplugin_continentCode;
//And for the country
$country=$details->geoplugin_countryCode;
//If continent is Europe
if($continent==="EU" && $country==="UK" || $continent!="EU"){
//Do action if country is UK or not from Europe
}else{
//Do action if country is in Europe , but its not UK
}
Edited the code a bit :)
You'll need to check IP ranges and block those that are in the ranges you don't want. Note that it's possible to get around these restrictions using a proxy or VPN or some such technology.
As Frank says, you will need to check the IP addresses against a geolocation database. An answered question on this topic already exists.
Below is a re-usable PHP function that uses 'ip-api.com' API to return location data on an IP and check it against a white-list of current EU member countries. The white-list is easy to maintain, which is good, as countries entering and leaving the EU are in a continual flux. The white-list was put together on July 24, 1018 with the data crossed-checked between the EU official website and Wikipedia. The 'ip-api.com' API is free for personal use (contact for commercial use), and can be run from your local server as well, and without registration or domain requirement.
function inEU($ip_input){
// Validate the IP address
if (filter_var($ip_input, FILTER_VALIDATE_IP) === false){
// Not a valid IP address - build error response
$message_string =
'<div style="width:100%; margin-top:50px; text-align:center;">'.
'<div style="width:100%; font-family:arial,sans-serif; font-size:24px; color:#c00; centered">'.
'ERROR: <span style="color:#fd0">Invalid IP Address</span>'.
'</div>'.
'</div>';
echo $message_string;
exit;
}
// Array of country names and country codes of European Union member countries
$eu_members = array(
'Austria','AT', 'Belgium','BE', 'Bulgaria','BG',
'Croatia','HR', 'Cyprus','CY', 'Czech Republic','CZ',
'Denmark','DK', 'Estonia','EE', 'Finland','FI',
'France','FR', 'Germany','DE', 'Greece','GR',
'Hungary','HU', 'Ireland','IE', 'Italy','IT',
'Latvia','LV', 'Lithuania','LT', 'Luxembourg','LU',
'Malta','MT', 'Netherlands','NL', 'Netherlands Antilles','AN',
'Poland','PL', 'Portugal','PT', 'Romania','RO',
'Slovakia','SK', 'Slovenia','SI', 'Spain','ES',
'Sweden','SE', 'United Kingdom','GB','UK'
);
$query_url = 'http://ip-api.com/json/'.$ip_input; // Build query URL for IP to JSON Data request
$ip_data_fetched = file_get_contents($query_url); // Return IP Data JSON as a string
$ip_data_fetched = utf8_encode($ip_data_fetched); // Encode returned JSON string to utf-8 if needed
$ip_data = json_decode($ip_data_fetched); // Decode utf-8 JSON string as PHP object
// Get the Country and Country Code for the IP from the returned data
$country = $ip_data->country; // Country Name (i.e; 'United States')
$countryCode = $ip_data->countryCode; // Country Code (i.e; 'US')
// Check the EU members array for match to either country or country code
$in_EU = false; // Ref for function boolean value returned - set false
$num_members = count($eu_members); // Number of indexes in EU members array (not # of members)
for ($i = 0; $i < $num_members; $i++){
$lc_eu_members = strtolower($eu_members[$i]);
if ($lc_eu_members === strtolower($country) || $lc_eu_members === strtolower($countryCode)){
$in_EU = true;
break;
}
}
return $in_EU;
}
And to use the function...
if (inEU( $ip )){
// IP address IS in an EU country
}
else {
// IP address IS NOT in an EU country
}
This function also cross-checks the returned location data in the same loop, so if there is a typo in one var, it would still find the location using the other var. For both to be wrong is not likely.
Unlike the 'geoplugin.net' API in Quadcore's example, which only checks on a continent value of 'EU', this function checks it against actual EU member countries.
This function can also be easily be adapted to work with many other IP to location API's that return a JSON response, including the 'geoplugin.net' API in Quadcore's example. It can easily be adapted as an 'allow only' white-list, rather than 'ban' white-list.
Hope this helps!

How to get explode #img::value to lookup in my database

I want to get value from my content such as #img::56:
#img::56 => value=56 to get record from datatabase mysql_query("select * from tblgallery where g_id=56");.
Tara Angkor Hotel is the first 4-Star Luxury Hotel built in the mystical land of Angkor. #img::56 Ideally and #youtube::https://www.youtube.com/watch?v=k4YRWT_Aldo conveniently located, Tara Angkor Hotel is situated only 6 km from the World Heritage site of Angkor Wat Temples, 15 min drive from the Siem Reap International Airport, a few minutes stroll to the Angkor National Museum and #img::41 a short ride to the city town center with an array of Cambodian souvenirs, shopping and culture.
I want to get result
Tara Angkor Hotel is the first 4-Star Luxury Hotel built in the mystical land of Angkor. mysql_query("select * from tblgallery where g_id=56") Ideally and <iframe width="560" height="315" src="//www.youtube.com/embed/k4YRWT_Aldo" frameborder="0" allowfullscreen></iframe> conveniently located, Tara Angkor Hotel is situated only 6 km from the World Heritage site of Angkor Wat Temples, 15 min drive from the Siem Reap International Airport, a few minutes stroll to the Angkor National Museum and mysql_query("select * from tblgallery where g_id=41") a short ride to the city town center with an array of Cambodian souvenirs, shopping and culture.
If I understand your question, you want to retrieve the 56 from the string #img::56?
If so it can be done as follows.
$string = '#img::56';
// Explode the string as the delimiter.
$components = explode('::', $string);
// Ensure the components array has two elements.
if(count($components) < 2) {
// Do something here to indicate an error has occurred.
//Throw an exception (preferred) or emit an error
}
$id = $components[1];
// You can use even more type checking here to ensure you have the right piece of data.
if(!ctype_digit($id)) {
//Throw an exception (preferred) or emit an error
}
// Accessing the database using a PDO object and prepared statements
$pdo = new \PDO('mysql:host=...', 'username', 'password')
$statement = $pdo->prepare('SELECT * FROM tblgallary WHERE g_id = :id');
$statement->bindParam(':id', $id, \PDO::PARAM_INT);
if(!$statement->execute()) {
//Throw an exception (preferred) or emit an error
}
$result = $statement->fetchAll(\PDO::FETCH_ASSOC);
// End the database connection
$pdo = null;
Now you have the id. If you need the $id to be an integer you can type cast it with (int) $components[1] instead.
Hope this helps.

Google Maps API with PHP to find distance between two locations

On my current project, which is a delivery system, I have a list of available delivery drivers, which is shown on an orders page. But what I need is to show the distance each delivery is from the customers address. The distance should be shown next to each driver's name. Anyone have any clues on how I would go about this?
Assuming that you want driving distance and not straight line distance, you can use the Directions web service:
You need to make an http or https request from your PHP script and the parse the JSON or XML response.
Documentation:
https://developers.google.com/maps/documentation/directions/
For example:
Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (JSON)
http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (XML)
http://maps.googleapis.com/maps/api/directions/xml?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
Note that there are usage limits.
You can easily calculates the distance between two address using Google Maps API and PHP.
$addressFrom = 'Insert from address';
$addressTo = 'Insert to address';
$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;
You can get the getDistance() function codes from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/
this will out seconds between 2 location
$origin =urlencode('Optus Sydney International Airport, Airport Drive, Mascot NSW 2020, Australia');
$destination = urlencode('Sydney NSW, Australia');
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$origin&destinations=$destination&key=your_key";
$data = #file_get_contents($url);
$data = json_decode($data,true);
echo $data['rows'][0]['elements'][0]['duration']['value'];

Put XML string (node value) in server text file and retrieve and echo it again (PHP)

This is my problem. I'm trying to retrieve a value from an XML url (from last.fm api). For example the biography of an artist.
I already know that I can do it simply like this (e.g. for Adele):
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
echo $info;
?>
This returns:
Adele Laurie Blue Adkins, (born 5 May 1988), is a Grammy Award-Winning English singer-songwriter from Enfield, North London. Her debut album, <a title="Adele - 19" href="http://www.last.fm/music/Adele/19" class="bbcode_album">19</a>, was released in January 2008 and entered the UK album chart at #1. The album has since received four-times Platinum certification in the UK and has sold 5,500,000 copies worldwide. The album included the hugely popular song <a title="Adele – Chasing Pavements" href="http://www.last.fm/music/Adele/_/Chasing+Pavements" class="bbcode_track">Chasing Pavements</a>. 19 earned Adele two Grammy Awards in February 2009 for Best New Artist and Best Female Pop Vocal Performance.
I would now like to put that result in a text file and store it on a folder on my website, for example: "http://mysite.com/artistdescriptions/adele.txt".
I've already tried:
<?php
$file_path = $_SERVER['DOCUMENT_ROOT'].'/artistdescriptions/adele.txt';
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
file_put_contents($file_path, serialize($info));
$file_contents = file_get_contents($file_path);
if(!empty($file_contents)) {
$data = unserialize($file_contents);
echo $data;
}
?>
But this unfortunately didn't work. Any help would be greatly appreciated!
Echo call magic method __toString(), but serialize doesn't, and in SimpleXMLElement isn't serialize allowed, so it throw an Exception. But you can call __toString() magic method by yourself, and this solve you problem.
Replace your line with mine
$info = $xml->artist->bio->summary->__toString();

Categories