PHP simplexml_load_file with special chars in URL - php

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

Related

Trying to get property of non-object geolocation google API

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!

How To Pull JSON Data Using PHP

I'm trying to create a very simple php script that can pull data from a JSON file (array?) and echo it to the page. Sadly, I'm a complete newbie when it comes to PHP.
My goal is to dump all IP addresses and the corresponding client version into an output like this...
"127.0.0.1" "/Satoshi:0.9.1/"
"127.0.0.2" "/Satoshi:0.9.0/"
"127.0.0.3" "/Satoshi:0.9.0/"
"127.0.0.4" "/Satoshi:0.9.1/"
I can get the code to dump all data, but I'm not sure how to pull the ip and version without the ip and client version being named.. If that even makes sense?
Here is the code. What do I need to make it dump the correct data?
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$JSON = file_get_contents($url);
echo $JSON;
$data = json_decode($JSON);
var_dump($data);
?>
Thanks for your help!
Something like
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$data = (array)$data; // cast from stdClass to array, as results have int keys
foreach($data['nodes'] as $results){
echo $results[0]. " ". $results[3]."<br />";
}
?>
It doesn't makes much sense to convert an array of hashes into the one of some non-named entities. I guess that all you need is to dump it in the following way:
foreach($data as $t)
{
echo("ip=".$t->ip." ua=".$t->ua);
}
I don't think there is any reason to cast to an array. Just process the returned object. This one has the double quotes as requested as well.
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$json = file_get_contents($url);
$data = json_decode($json);
foreach($data->nodes as $results){
echo "\"".$results[0]."\" \"".$results[3]."\"<br />";
}
?>

how to display SimpleXMLElement with php

Hi I have never used xml but need to now, so I am trying to quickly learn but struggling with the structure I think. This is just to display the weather at the top of someones website.
I want to display Melbourne weather using this xml link ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml
Basically I am trying get Melbourne forecast for 3 days (what ever just something that works) there is a forecast-period array [0] to [6]
I used this print_r to view the structure:
$url = "linkhere";
$xml = simplexml_load_file($url);
echo "<pre>";
print_r($xml);
and tried this just to get something:
$url = "linkhere";
$xml = simplexml_load_file($url);
$data = (string) $xml->forecast->area[52]->description;
echo $data;
Which gave me nothing (expected 'Melbourne'), obviously I need to learn and I am but if someone could help that would be great.
Because description is an attribute of <area>, you need to use
$data = (string) $xml->forecast->area[52]['description'];
I also wouldn't rely on Melbourne being the 52nd area node (though this is really up to the data maintainers). I'd go by its aac attribute as this appears to be unique, eg
$search = $xml->xpath('forecast/area[#aac="VIC_PT042"]');
if (count($search)) {
$melbourne = $search[0];
echo $melbourne['description'];
}
This is a working example for you:
<?php
$forecastdata = simplexml_load_file('ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml','SimpleXMLElement',LIBXML_NOCDATA);
foreach($forecastdata->forecast->area as $singleregion) {
$area = $singleregion['description'];
$weather = $singleregion->{'forecast-period'}->text;
echo $area.': '.$weather.'<hr />';
}
?>
You can edit the aforementioned example to extract the tags and attributes you want.
Always remember that a good practice to understand the structure of your XML object is printing out its content using, for instance, print_r
In the specific case of the XML you proposed, cities are specified through attributes (description). For this reason you have to read also those attributes using ['attribute name'] (see here for more information).
Notice also that the tag {'forecast-period'} is wrapped in curly brackets cause it contains a hyphen, and otherwise it wouldn generate an error.

getting xml from URL into variable

I am trying to get an xml feed from a url
http://api.eve-central.com/api/marketstat?typeid=1230&regionlimit=10000002
but seem to be failing miserably. I have tried
new SimpleXMLElement,
file_get_contents and
http_get
Yet none of these seem to echo a nice XML feed when I either echo or print_r. The end goal is to eventually parse this data but getting it into a variable would sure be a nice start.
I have attached my code below. This is contained within a loop and $typeID does in fact give the correct ID as seen above
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
$xml = new SimpleXMLElement($url);
print_r($xml);
I should state that the other strange thing I am seeing is that when I echo $url, i get
http://api.eve-central.com/api/marketstat?typeid=1230®ionlimit=10000002
the &reg is the registered trademark symbol. I am unsure if this is "feature" in my browser, or a "feature" in my code
Try the following:
<?php
$typeID = 1230;
// set feed URL
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
// read feed into SimpleXML object
$sxml = simplexml_load_file($url);
// then you can do
var_dump($sxml);
// And now you'll be able to call `$sxml->marketstat->type->buy->volume` as well as other properties.
echo $sxml->marketstat->type->buy->volume;
// And if you want to fetch multiple IDs:
foreach($sxml->marketstat->type as $type){
echo $type->buy->volume . "<br>";
}
?>
You need to fetch the data from the URL in order to make an XML object.
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
$xml = new SimpleXMLElement(file_get_contents($url));
// pre tags to format nicely
echo '<pre>';
print_r($xml);
echo '</pre>';

How find Distance between two addresses through php

i am looking for some help to find the distance between two address through php
as i can not use the google maps api. so get a way from this post
Distance between two addresses
but i need to know how can send the request using URL pattern
and grab the repose to save them in database.
http://maps.google.com/maps/api/directions/xml?origin=550+Madison+Avenue,+New+York,+NY,+United+States&destination=881+7th+Avenue,+New+York,+NY,+United+States&sensor=false
thanks for any suggestion.
///////////////
After these answers i am there
$customer_address_url = urlencode($customer_address);
$merchant_address_url = urlencode($merchant_address);
$map_url = "http://maps.google.com/maps/api/directions/xml?origin=".$merchant_address_url."&destination=".$customer_address_url."&sensor=false";
$response_xml_data = file_get_contents($map_url);
$data = simplexml_load_string($response_xml_data);
XML response is visible when i put this url : http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false
but can not printing through
echo "<pre>"; print_r($data); exit;
You can try this..
$url = "http://maps.google.com/maps/api/directions/xml?origin=550+Madison+Avenue,+New+York,+NY,+United+States&destination=881+7th+Avenue,+New+York,+NY,+United+States&sensor=false";
$data = file_get_contents($url);
Now $data contains resulting xml data. You can parse this xml data using..
http://php.net/manual/simplexml.examples.php
use the haversine formula
Also check https://developers.google.com/maps/documentation/distancematrix/

Categories