I'm working in to get the latitude and longitude from google maps through the geolocation API. I have tried many times but always is showing this error:
Trying to get property of non-object in C:\wamp64\www\index3.php on line 16
The issue is that I'm not able to get the info from the $url so then, cannot get the latitude and longitude.
I changed my code and now it is, but still with no working.
<php
$address = urlencode('BTM 2nd Stage,Bengaluru,Karnataka,560076');
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=*************************************";
$json = file_get_contents($url); // I tried with the # symbol and without it
$data=json_decode($json);
echo ($data->results[0]->geometry->location->lat);
?>
And also I used this one:
<php
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$encode = urlencode($address);
$key = "insert key here";
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$encode}&key={$key}";
$json = file_get_contents($url); // I tried with the # symbol and without it
$data = json_decode($json);
echo "Latitud".($data->results[0]->geometry->location->lat);
?>
Without the # symbol I have this error line
Warning: file_get_contents() has been disabled for security reasons in [...][...] on line 8
change http
to https in your request url.
As Abrucius, you msut use HTTPS or google will deny the request. You must also encode the address or else you will get a "Bad request" error.
<?php
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$encode = urlencode($address);
$key = "insert key here";
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$encode}&key={$key}";
$json = file_get_contents($url);
$data = json_decode($json);
echo ($data->results[0]->geometry->location->lat);
Outputs: 12.9082396
replace following code
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyDjWI3J9CNlANoB5PXNKq3nz1ZbYeOrNGE";
to
$address = urlencode('BTM 2nd Stage,Bengaluru,Karnataka,560076');
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyDjWI3J9CNlANoB5PXNKq3nz1ZbYeOrNGE";
You have provided http in the url, it should be https. Try below code that will help you. You have to use urlencode() because api will not allow space in the address, so you have to encode.
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$address = urlencode($address);
$url = "https://maps.google.com/maps/api/geocode/json?address={$address}&key=***************************";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
echo "<pre>";print_r($resp["results"][0]['geometry']['location']['lat']);
Try this code will work for sure
WillParky93's answer seems to work fine for me. Maybe try following the next link to allow https wrappers:
How to get file_get_contents() to work with HTTPS?
...or post the error you're getting so we can help you out
I just solved this issue, I was getting this error because of a proxy configuration. I was testing into a network with a proxy configuration. So, the proxy is not allowing me to connect with the Google database. Then I tried to connect with a different network and it worked perfectly. Thank you guys for your aid!
Related
I am trying to send json request and store the response in a variable using php using the below code
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=xxx&app_code=yyy&searchtext=3891 Delwood Drive, Powell, OH, United States";
$json = file_get_contents($hmaps_request);
$details = json_decode($json, TRUE);
I could not get anyerrors as well as any response. But if i paste the url in browser i could get json response.
Detects Your Problem
If you read the $http_response_header array (generated by file_get_contents() call), you'd find out that you got a "400 Bad Request" response and thus got nothing. So something must have gone wrong with your URL.
After a brief inspection, I think perhaps its your "searchtext" parameter that's blocking you. For starter, valid URL query don't usually have spaces in it. Probably why the API server says that you're a "Bad Request".
Normally, you need to properly escape the URL query string to have a proper URL. Modern browsers are very good at translating it for you seamlessly and automatically so you might not have this problem by using the URL directly in browsers.
Solution
Let's put this theory to a test. We'll use http_build_query() to escape your query query parameters:
(For privacy reason, the parameters are modified. Please substitute the query variables)
$query = http_build_query([
'app_id' => 'your-app-id',
'app_code' => 'your-app-code',
'searchtext' => '123 Some Address',
]);
$url = 'https://geocoder.api.here.com/6.2/geocode.json?' . $query;
$json = file_get_contents($url);
$details = json_decode($json, TRUE);
var_dump($details);
I seem to get proper decoded response now. Try it yourself.
There is an error in your request URL change the request URL
From
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891 Delwood Drive, Powell, OH, United States";
To
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891+Delwood+Drive+Powell+OH+United+States";
Here is the full code
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891+Delwood+Drive+Powell+OH+United+States";
$json = file_get_contents($hmaps_request);
$details = json_decode($json, TRUE);
print_r($details);
I think the error in your request URL. Please check below code.
$url = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891 Delwood Drive, Powell, OH, United States";
$url = str_replace(" ","%20",$url);
$json = #file_get_contents($url);
$details = json_decode($json, TRUE);
print_r($details);
Im new to php and tried to get a json object from the twitch API to retrieve one of its values and output it. i.e
i need to get the information from this link: https://api.twitch.tv/kraken/users/USERNAME/follows/channels/CHANNELSNAME
plus i need to to something so i can modify the urls USERNAME and CHANNELSUSERNAME. I want it to be a api to call for howlong user XY is following channelXY and this will be called using nightbots $customapi function.
the date i need from the json is "created_at"
Since we were able to clear out the errorsheres the final PHP file that works if anyone encounters similiar errors:
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
?>
You have a typo in your code on the first line and you're not storing the result of your json_decode anywhere.
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
You have to call the page this way page.php?username=yeroise&channel=ceratia in order to output the created_at value for this user and this channel.
In your code you're using 2 different ways to get the content of the page and you only need one (either file_get_contents or using CURL), I chose file_get_contents here as the other method adds complexity for no reason in this case.
Currently, I am trying to use the Twitch API to grab Twitch stats such as current viewers, Title, and more I am running into an issue with #File_Get_Contents when using this my request seem to be delayed or not getting them as quick as I refresh, i.e. I think the results may be cache'd.
For example here is my old code
$twitch = json_decode(curl_get_file_contents('https://api.twitch.tv/kraken/channels/'.$twitch_channel), true);
$display_name = $twitch['display_name'];
$game = $twitch['game'];
$status = $twitch['status'];
$url = $twitch['url'];
$avatar = $twitch['logo'];
$views = $twitch['views'];
$followers = $twitch['followers'];
The main issue with this is it didnt seem like it updated every time I refreshed, so I looked into using cURL for better results + I heard it's much quicker with load time!
Here is my current curl code
$requesturl='https://api.twitch.tv/kraken/channels/' . $twitch_username;
$ch=curl_init($requesturl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cexecute=curl_exec($ch);
curl_close($ch);
$twitch = json_decode($cexecute,true);
$display_name = $twitch['display_name'];
$game = $twitch['game'];
$status = $twitch['status'];
$url = $twitch['url'];
$avatar = $twitch['logo'];
$views = $twitch['views'];
$followers = $twitch['followers'];
Your log is showing PHP Notice, You don't have any error. I change a lil bit your code to test it and It's working. So you're probably just no printing your vars.
Check your code with a print_r online
So ultimnately I figured out what the issue was, it's XAMP Curl not working for whatever reason. It's setup properly in the PHP.ini, I have the Two .DLL in my Sys32. So I dont know why this isn't working
I'm trying to regularly retrieve JSON album data from the Last.FM API, and since they don't support JSONP I'm using a PHP Proxy to circumvent the cross-domain limitation. Here's my PHP proxy:
<?php
$artist = $_GET["artist"];
$album = $_GET["album"];
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=APIKEY=' . $artist . '&album=' . $album . '&format=json');
echo $content;
?>
As you can see I'm using GET to specify the artist and album, so the URL would look like albumartproxy.php?artist=Jake%20Bugg&album=Jake%20Bugg
But for some reason I get the following error when I try to run the proxy:
Warning: file_get_contents(http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=Jake Bugg&album=Jake Bugg&format=json) [function.file-get-contents]: failed to open stream: HTTP request failed! in /MYDOMAIN/albumartproxy.php on line 6
When I access the API URL directly it works? Can someone help? What am I doing wrong?
You'll need to urlencode() the GET parameters that you are passing along with the request.
You need urlencode() the GETs, like so:
<?php
$apikey = "273f3dc84c2d55501f3dc25a3d61eb39";
$artist = urlencode($_GET["artist"]);
$album = urlencode($_GET["album"]);
$autocorrect = 0;
$content = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect;
echo file_get_contents($content);
?>
Sample output: http://pastie.org/8114551
Hope this helps!
I'm attempting to retrieve a local weather forecast, based on the IP of the user.
I'm using geoplugin.net to get the user location and feed the city and country name to the Google Weather API.
//Get user IP
$ip = $_SERVER['REMOTE_ADDR'];
$geolocation = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
$geo_city = $geolocation['geoplugin_city'];
$geo_country = $geolocation['geoplugin_countryName'];
$file = "http://www.google.com/ig/api?weather=".$geo_city.",".$geo_country;
$xml = simplexml_load_file($file);
//Echo content of retrieved XML for debugging purposes
echo "<pre>";
print_r($xml);
echo "</pre>";
It works well for most cases, but when I try it on my own IP, I get Søborg, Denmark (which is not 100% accurate, but close enough) and that gives me an almost empty response from the weather API.
The main suspect in the case, is the dastardly "ø"-character.
The XML that I want can be seen here: http://www.google.com/ig/api?weather=S%C3%B8borg,Denmark
The XML that I'm getting can be seen here: http://www.google.com/ig/api?weather=S
When I type this URL into the browser it works fine:
http://www.google.com/ig/api?weather=Søborg,Denmark
When I use this version it works as well (in the browser):
http://www.google.com/ig/api?weather=S%C3%B8borg,Denmark
but this version returns the forecast for Borg,Syddanmark:
http://www.google.com/ig/api?weather=S%26oslash%3Bborg,Denmark
None of the above returns the desired result, when fed to the simplexml_load_file().
As stated, I suspect that it is a character set issue, but I can't figure out what to do about it.
What is the correct way to solve it?
I know that I can use latitude and longtitude as parameters for Google Weather API instead, but that's just circumventing the problem, not solving it.
If you URL-decode S%26oslash%3Bborg you'll see that this string corresponds to Søborg which gives us Søborg after we decode HTML entities like so:
$city = 'S%26oslash%3Bborg,Denmark';
echo $city = rawurldecode($city);
//prints Søborg,Denmark
echo $city = html_entity_decode($city, 0, 'UTF-8');
//prints Søborg,Denmark
echo $city = rawurlencode($city);
//prints S%C3%B8borg%2CDenmark
And then:
$xml = file_get_contents('http://www.google.com/ig/api?weather='.$city);
$xml = mb_convert_encoding($xml, 'UTF-8');
$xml = simplexml_load_string($xml);
echo $xml->weather->forecast_information->city['data'];
Outputs expected:
Søborg, Capital Region of Denmark
It does indeed sound like a character set issue. Have you tried converting the URL to another encoding, e.g. using iconv, before passing the result into simplexml_load_file()?
Try this out:
$file = "http://www.google.com/ig/api?weather=" . $geo_city . "," . $geo_country;
$data = file_get_contents($file);
$data = mb_convert_encoding($data, "UTF-8", "ISO-8859-2");
$xml = simplexml_load_string($data);
echo "<pre>"; print_r($xml); echo "</pre>";
It's taken from this maybe similar thread: https://stackoverflow.com/a/5136549/949476