I'm using this function to get the coordinates of any address:
function getCoordinates($address) {
$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
$address = str_replace("-", "+", $address); // replace all the "-" with "+" sign to match with google search pattern
$url = "http://maps.google.com/maps/api/geocode/json?address=$address";
$response = file_get_contents($url);
$json = json_decode($response,TRUE); //generate array object from the response from the web
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
}
Sometimes it works and sometimes it only gets "," for the same address.
Do I need to use another function?
try this
$url = "http://maps.google.com/maps/api/geocode/json?address=".$address;
Related
I have the following link as a string in php:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
I am trying to add the word BIG before the number so at the end I will have:
$url = 'http://www.example.com/assets/images/temp/big10.jpg';
I am currently accomplishing that by using explode on / then adding big to the last array. My only issue is that in the future, this link might have less / i.e.: http://www.example.com/assets/10.jpg. In this case, my explode statement will not work. Is there a better way to add the word big after the last occurance of /?
I also came up with this method:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$filename = substr(strrchr($url, "/"), 1); // returns 10.jpg
$newfilename = 'big'.substr(strrchr($url, "/"), 1); // returns big10.jpg
$newurl = str_replace($filename,$newfilename,$url); // replaces 10.jpg with big.jpg
According to description as mentioned into above question as a solution to it please try executing following code snippet .
<?php
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$fileName = basename($url);
$newFileName = 'big' . $fileName;
$url = str_ireplace($fileName, $newFileName, $url);
echo $url;
?>
Explode will always work. However, if you want a neater way to do it you can do this:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$newurl = substr_replace($url, "big", strrpos($url, '/') + 1, 0);
This will give your expected result: http://www.example.com/assets/images/temp/big10.jpg
There are quite a few methods to accomplish what you're wanting.
To me the easiest would be to use pathinfo to extract the filename, and then append your prefix to the basename.
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$pathinfo = pathinfo($url);
var_dump($pathinfo['dirname'] . '/' . $prefix . $pathinfo['basename']);
Result: https://3v4l.org/3MkIG
string(51) "http://www.example.com/assets/images/temp/big10.jpg"
Object oriented approach: https://3v4l.org/aF5lf
class FileNamePrefixer extends SplFileInfo
{
public function addPrefix($prefix)
{
return $this->getPathInfo() . '/' . $prefix . $this->getBaseName();
}
}
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$fileInfo = new FileNamePrefixer($url);
var_dump($fileInfo->addPrefix('big'));
Another method is to use preg_replace to specify a pattern of words you want to replace.
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$new_url = preg_replace('/([\w|\s|-]+)(\.\w+)$/', $prefix . '$1$2', $url);
var_dump($new_url);
The pattern ([\w|\s|-]+)(\.\w+)$ means; at the end of the string, look for a word (characters: a-z, A-Z, 0-9, _, space, and -), followed by a period, which is followed by another word and store them in variables $1 and $2.
Result: https://3v4l.org/6e8d7
string(51) "http://www.example.com/assets/images/temp/big10.jpg"
Note that if your URL will optionally contain fragments or a querystring, the preg_replace pattern above will not work. Instead you would need to account for them as optional like so:
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg?foo=bar&baz=foo#foobar';
$new_url = preg_replace('/([\w|\s|-]+)(\.\w+)(\?.+)?(#.+)?$/', $prefix . '$1$2$3$4', $url);
var_dump($new_url);
The pattern (\?.+)?(#.+)? means; optionally find ? followed by anything, and optionally find # followed by anything and store them in variables $3 and $4 with the original pattern.
Result: https://3v4l.org/uuYrO
string(74) "http://www.example.com/assets/images/temp/big10.jpg?foo=bar&baz=foo#foobar"
I'm uploading a csv file and getting address field in $address variable, but when I pass $address to google maps, its showing me error,
file_get_contents(http://maps.googleapis.com/maps/api/geocode/json?address=9340+Middle+River+Street%A0%2COxford%2CMS%2C38655): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request.
I searched for its solution, I found one that to encode only address but its also not working for me...
CODE
if (!empty($address)) {
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address));
$geo = json_decode($geo, true);
if ($geo['status'] = 'OK') {
if (!empty($geo['results'][0])) {
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
$mapdata['latitude'] = $latitude;
$mapdata['longitude'] = $longitude;
return $mapdata;
} else {
$mapdata['latitude'] = "";
$mapdata['longitude'] = "";
return $mapdata;
}
}
Error is at line
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address));
Have I missed anything.!
Any help is much appreciated.. Thanks
you need to use google api key
function getLatLong($address){
if(!empty($address)){
//Formatted address
$formattedAddr = str_replace(' ','+',$address);
//Send request and receive json data by address
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false');
$output = json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
//Return latitude and longitude of the given address
if(!empty($data)){
return $data;
}else{
return false;
}
}else{
return false;
}
}
Use getLatLong() function like the following.
$address = 'White House, Pennsylvania Avenue Northwest, Washington, DC, United States';
$latLong = getLatLong($address);
$latitude = $latLong['latitude']?$latLong['latitude']:'Not found';
$longitude = $latLong['longitude']?$latLong['longitude']:'Not found';
To specify a Google API key in your request, include it as the value of a key parameter.
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey');
i hope this will help you.
It looks like the problem is with your data set. The part of the url that is being encoded as %A0 by urlencode($address) is a special non-breaking space character, rather than a regular space.
See here for more information on the difference:
Difference between "+" and "%A0" - urlencoding?
The %A0 character isn't accepted in this context, but you can do a quick str_replace() on the result of urlencode() to replace all these special space characters with the + symbols that regular spaces would have resulted in.
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . str_replace('%A0', '+', urlencode($address)));
I am using ipinfo.io for some simple lookups, but I have one little problem with echo $details->org; It outputs "AS15169 Google Inc.", but I want only the ISP part so "Google Inc.".
Example code:
<?
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details($_SERVER['REMOTE_ADDR']);
echo $details->org;
?>
Example output: http://ipinfo.io/8.8.8.8/org
Need some help, anyone?
If you just want the org field you can query http://ipinfo.io/{$ip}/org which will give you the org as a string, which will save you from having to parse any JSON:
$org = file_get_contents("http://ipinfo.io/{$ip}/org");
We can split the org string into the ASN and name by exploding on the first space:
list($asn, $name) = explode(" ", $org, 2);
Putting it all together we get:
function org_name($ip) {
$org = file_get_contents("http://ipinfo.io/{$ip}/org");
list($asn, $name) = explode(" ", $org, 2);
return $name;
}
echo org_name("8.8.8.8");
// => Google Inc.
echo org_name("189.154.55.170");
// => Uninet S.A. de C.V.
echo org_name("172.250.147.230");
// => Time Warner Cable Internet LLC
See http://ipinfo.io/developers for more details about the different endpoints, and rate limits.
Use regex to find anything between word boundaries that starts with AS and has one or more digits followed by a space and then replace it with a blank string.
I'm not great with regex so someone might come in with a better solution that this. But I tested it at PHP Live Regex and it worked for the few test cases I tried.
<?
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details($_SERVER['REMOTE_ADDR']);
$org = preg_replace('/\bAS\d+\s\b/i', '', $details->org);
echo $org;
?>
I have a problem when I try to convert an address into latitude and longitude via google service. My address is 1456 sok. no: 10/1 kat:8 Alsancak. The problem is when I write this address to url, correct result is returned, however when I use the php code below, I get zero results.
No problem with result :
http://maps.google.com/maps/api/geocode/json?address=1456%20sok.%20no:%2010/1%20kat:8%20Alsancak&sensor=true
Problem with php :
<?php
header('Content-Type: text/html; charset=utf-8');
getGoogleAddressCoordinates("1456 sok. no: 10/1 kat:8 Alsancak");
function getGoogleAddressCoordinates($address)
{
//$address = urlencode($address);
$address = str_replace(" ", "%20", $address);
$request = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $address . '&sensor=true');
$json = json_decode($request, true);
print_r ($json);
}
?>
The address 1456 sok. no: 10/1 kat:8 Alsancak is not valid. If you try it in google maps you get zero results, too.
Try it with: 1456 sok. 10/1 Alsancak and uncomment the line $address = urlencode($address); and clear the line $address = str_replace(" ", "%20", $address);.
The url should look like:
http://maps.google.com/maps/api/geocode/json?address=1456%20sok.%2010%2F1%20Alsancak&sensor=true
Have been searching for a solution for hours.
My entire WordPress theme validates, except this script I'm using to receive the last tweet:
<?php
$twitterUsername = get_option('of_twitter_username');
$username = $twitterUsername; // Your twitter username.
$prefix = ""; // Prefix - some text you want displayed before your latest tweet.
$suffix = ""; // Suffix - some text you want display after your latest tweet.
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";
function parse_feed($feed) {
$stepOne = explode("<content type=\"html\">", $feed);
$stepTwo = explode("</content>", $stepOne[1]);
$tweet = $stepTwo[0];
$tweet = str_replace("<", "<", $tweet);
$tweet = str_replace(">", ">", $tweet);
return $tweet;
}
$twitterFeed = file_get_contents($feed);
echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);
?>
The error, it seems, is:
$tweet = str_replace(">", ">", $tweet);
Not sure how to fix this.
Thanks for any help.
Replace the two str_replace calls with:
$tweet = html_entity_decode($tweet);
Maybe a simplier way (you don't need to parse) is to load http://search.twitter.com/search.json?q=from:the_username and make a json_decode of the result.
Then you can get the last tweet easily.