Get a query from url in php - php

I don't know how to do this in php. I am trying to get geocode data from openstreetmap.org but I need to do this in php.
In Javascript (and I have this working), it's:
<script type="text/javascript"
src="http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671">
</script>
I have that url but I don't know how to execute it in php.
I have tried:
<?php
$url = "http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671";
$response = file_get_contents($url);
?>
But this doesn't work. I tried the same with curl. Any ideas or is this type of query not possible in php?

Use this;
$xml = simplexml_load_file("http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671");
print_r($xml);
which will return you with an array of the values, see below;
SimpleXMLElement Object
(
[#attributes] => Array
(
[timestamp] => Thu, 22 Mar 12 18:31:11 +0000
[attribution] => Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.
[querystring] => format=xml&lat=43.642018&lon=-79.374671
)
[result] => 1, Yonge Street, Corktown, Toronto, Ontario, M5B2H1, Canada
[addressparts] => SimpleXMLElement Object
(
[house_number] => 1
[road] => Yonge Street
[suburb] => Corktown
[city] => Toronto
[county] => Toronto
[state] => Ontario
[postcode] => M5B2H1
[country] => Canada
[country_code] => ca
)
)
Then manipulate the data however you see fit.

It does return
<?xml version="1.0" encoding="UTF-8" ?>
<reversegeocode timestamp='Thu, 22 Mar 12 18:07:13 +0000' attribution='Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.' querystring='format=xml&lat=100&Lon=100'>
<error>Unable to geocode</error></reversegeocode>
That just means that there is no address for that particular coordinate.. This however has
http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=100
Read API if you need more details

Related

How to get value from parsed XML

This is my XML with name test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:test="http://www.test.com/rss/2.0">
<positionfeed>
<test:import user="accounts#test.com" site="www.test.com" />
<job>
<id>83762455</id>
<employer>Mount Ida College</employer>
<title>Assistant Professor, Dental Hygiene</title>
<description>As a faculty member, you will provide instruction in didactic courses, clinics, and/or labs in the Dental Hygiene Program.</description>
<postingdate>2016-10-21</postingdate>
<joburl>http://url.com</joburl>
<location>Newton, MA</location>
<category>Education</category>
</job>
<job>
<id>83762405</id>
<employer>Veterinary Orthopedic & Sports Medicine Group</employer>
<title>Overnight Recovery Technician</title>
<description>As a faculty member, you will provide instruction in didactic courses, clinics, and/or labs in the Dental Hygiene Program.</description>
<postingdate>2016-10-25</postingdate>
<joburl>http://url.com</joburl>
<location>Annapolis Junction, MD</location>
<category>Installer/Technician</category>
</job>
</positionfeed>
</rss>
This is my PHP page where I'm parsing it:
<?php
$languages = simplexml_load_file("test.xml");
print_r($languages);
foreach ($languages->job as $job) {
echo $job->title;
echo "<br>";
}
?>
I want:
job->id
job->title
and so on
=============================
print_r($languages) gives:
SimpleXMLElement Object ( [#attributes] => Array ( [version] => 2.0 )
[positionfeed] => SimpleXMLElement Object ( [job] => Array ( [0] =>
SimpleXMLElement Object ( [id] => 83762455 [employer] => Mount Ida
College [title] => Assistant Professor, Dental Hygiene [description]
=> As a faculty member, you will provide instruction in didactic courses, clinics, and/or labs in the Dental Hygiene Program.
[postingdate] => 2016-10-21 [joburl] => http://url.com [location] =>
Newton, MA [category] => Education ) [1] => SimpleXMLElement Object (
[id] => 83762405 [employer] => Veterinary Orthopedic & Sports Medicine
Group [title] => Overnight Recovery Technician [description] => As a
faculty member, you will provide instruction in didactic courses,
clinics, and/or labs in the Dental Hygiene Program. [postingdate] =>
2016-10-25 [joburl] => http://url.com [location] => Annapolis
Junction, MD [category] => Installer/Technician ) ) ) )
============================
I tried researching a lot.
If I remove below three lines manually the PHP code works fine and displays values as needed, but I am unable to remove them dynamically.
<rss version="2.0" xmlns:test="http://www.test.com/rss/2.0">
<test:import user="accounts#test.com" site="www.test.com" />
</rss>
So either of the way will work, if anyone can help, either help me to remove these three lines dynamically on load on PHP page else able to get values of the required nodes.
Again as description is long, I want:
job->id
job->title
and so on

Parse XML Data from URL

I have searched the site and found many resources to help me load and XML file to parse, however after following some of the examples, I can still not get this to work. What am I missing?
thanks
<?php
$url = 'http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=XML&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0';
$xml = simplexml_load_file($url) or die("feed not loading");
var_dump($xml);
?>
You're most likely confusing what you see in the browser under that URL with an XML document.
What you have at the URL
http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=XML&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0
is not an XML document. When you request that URL and you look into the response headers, you can see that it is a HTML document:
HTTP/1.1 200 OK
Content-Type: text/html;charset=ISO-8859-1
P3P: CP="IDC CON TEL CUR DEV SAM IND"
Date: Mon, 10 Aug 2015 15:50:46 GMT
Content-Language: en-US
Connection: Keep-Alive
Set-Cookie: X-Mapping-gjinjpae=F462690912B62A0C5476B15FCDB01A81; path=/
Set-Cookie: JSESSIONID=BC6666D2A357FB969A60E05E67B0888C; Path=/
Set-Cookie: JSESSIONID=700D01B2F92909260A05215F86AB8EE5; Path=/
Content-Length: 7147
You can also easily verify that with your browser by making use of the view source feature in your browser or by seeing, that the XML is not displayed "pretty".
However simplexml_load_file expects a well-formed XML document. In your case the main problem you've got is missing error handling. As you interact with a remote system, error handling is crucial for stable use, so make it part of your script:
Dealing with XML errors (SimpleXML - PHP Manual)
Next to that, as it's an HTML document and not an XML document, you need to parse it with a HTML parser - not an XML parser. So don't try with an XML parser at that stage, use a HTML parser first.
How do you parse and process HTML/XML in PHP? (Reference Q&A)
Edit:
The problem with that service is only when you request XML format. If you change the format parameter to JSON (&format=JSON) you can parse the data straight-away despite the wrong response content-type given:
$url = 'http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=JSON&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0';
$result = json_decode(file_get_contents($url));
print_r($result);
Gives:
Array
(
[0] => stdClass Object
(
[response] => stdClass Object
(
[query] => Sales
[location] => 95054
[highlight] => off
[totalresults] => 25406
[start] => 1
[end] => 9
[radius] => 25
[pageNumber] => 0
[results] => Array
(
[0] => stdClass Object
(
[jobtitle] => Sales
[zip] => 95101
[company] => Commercial Janitorial Company
[city] => San Jose
[state] => CA
[country] => US
[date] => 2015-07-14
[url] => http://api.l5srv.net/job_search/api/web/get_job.srv?token=3aeyzv6V2SA%2BKYF5lzqWmxyivVwoE3LFernO291sVVpLbWCG9bBAbVO%2BCGXuN1V%2F9QMmDY3KeK5iYg2phrtjypXtQ82Jngf1q8zQIzix14EuBlSL96sqjffsuHozTZ4SJ6Mf%2B%2BVwRrC65gRtKxH6wg0F50WEZtnD9Xv0%2Bxc2GMhFMszKNEOyrfCNg5YTn%2Flj
[snippet] => Company Description:
We are a Christian owned janitorial company doing business here in the Bay Area for nearly 40 years. You do not have to be Christian to work for us.
We operate in a fast paced, f
[onmousedown] => l5_trk(this)
)
[1] => stdClass Object
(
[jobtitle] => Sales
[...]
The code coming from this server is not valid XML. Try this:
<?php
$url = 'http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=XML&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0';
$data = file_get_contents($url);
$data = '<' . '?xml version="1.0" encoding="UTF-8"?' . '>' . str_replace(array("<", ">"), array("<", ">"), $data);
$xml = simplexml_load_string($data) or die("feed not loading");
var_dump($xml);

Parse XML with incresing tag values using PHP

I'm using some api which returns the list of transactions done by the user in XML format. This is how it looks like.
<Response>
<Status>00</Status>
<STMT>
<T0>
<ID>25624</ID>
<DATE>30 JUNE 2014</DATE>
<Amount>1500</Amount>
</T0>
<T1>
<ID>11495</ID>
<DATE>29 JUNE 2014</DATE>
<Amount>1000</Amount>
</T1>
<T2>
----
----
----
</STMT>
<Bal>55</Bal>
</Response>
Now, how do we get those values inside STMT tags? I tried this, but didn't work.
$result=simplexml_load_string($xmlstring);
$i='0';
$tx ='T'.$i;
while ($result->STMT->$tx) {
$result->STMT->$tx->ID;
$tx='T'.strval(intval($i++));
}
Please help.
Actually this is just straightforward. Do something like this:
$xml_string = '<Response><Status>00</Status><STMT> <T0> <ID>25624</ID> <DATE>30 JUNE 2014</DATE> <Amount>1500</Amount> </T0> <T1> <ID>11495</ID> <DATE>29 JUNE 2014</DATE> <Amount>1000</Amount> </T1> <T2> <ID>11496</ID> <DATE>28 JUNE 2014</DATE> <Amount>500</Amount> </T2></STMT><Bal>55</Bal></Response>';
$xml = simplexml_load_string($xml_string);
$stmt = $xml->STMT;
$stmt = json_decode(json_encode($stmt), true);
echo '<pre>';
print_r($stmt);
Output:
Array
(
[T0] => Array
(
[ID] => 25624
[DATE] => 30 JUNE 2014
[Amount] => 1500
)
[T1] => Array
(
[ID] => 11495
[DATE] => 29 JUNE 2014
[Amount] => 1000
)
[T2] => Array
(
[ID] => 11496
[DATE] => 28 JUNE 2014
[Amount] => 500
)
)
It works. You didn't echo the result...
echo $result->STMT->$tx->ID . "\n";
Also, $i++ should be changed to ++$i.

Retrieving locale out of timezone_identifier -php

Is there an easy way to retrieve the locale from the timezone_identifier?
For example:
date_default_timezone_set('Europe/Berlin');
The Locale in that case should de_DE.
As deceze said there is no possiblity of this. But you can get location information from timezone. as php.net says
$tz = new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
will output
Array
(
[country_code] => CZ
[latitude] => 50.08333
[longitude] => 14.43333
[comments] =>
)
Array
(
[country_code] => CZ
[latitude] => 50.08333
[longitude] => 14.43333
[comments] =>
)
No, because there's no such 1:1 correlation. Take Belgium for example, where they officially speak three languages in the same timezone.

Getting values from specified keys

i use imdb api
$homepage = file_get_contents('http://www.imdbapi.com/?i='.$imdbID);
$arr = json_decode($homepage);
In $arr i have all data about related movie.
Maguire [Year] => 1996 [Rated] => R [Released] => 13 Dec 1996 [Genre] => Comedy, Drama, Romance, Sport [Director] => Cameron Crowe [Writer] => Cameron Crowe [Actors] => Tom Cruise, Cuba Gooding Jr., Renée Zellweger, Kelly Preston [Plot] => When a sports agent has a moral epiphany and is fired for expressing it, he decides to put his new philosophy to the test as an independent with the only athlete who stays with him. [Poster] => http://ia.media-imdb.com/images/M/MV5BMTkxNjc2NjQwOF5BMl5BanBnXkFtZTcwMDE2NDU2MQ##._V1_SX320.jpg [Runtime] => 2 hrs 19 mins [Rating] => 7.2 [Votes] => 97329 [ID] => tt0116695 [Response] => True )
what i want is that reaching specified key's value.
Is there a function like that? For example , i will give the key=> Actors and get all actors?
:/ Like this?
$homepage = file_get_contents('http://www.imdbapi.com/?i='.$imdbID);
$arr = json_decode($homepage, true);
print($arr['Actors']);

Categories