PHP How to get url and load it xml

I am trying to send this request:

http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK

Into a web service and pull and analyze a bunch of fields, namely:

// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.

I'm doing it:

$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";

Can someone please provide the correct code to view the results and get the values?

+3
source share
3 answers

Since the answer is XML, you can use SimpleXML :

$url = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
$xml = new SimpleXMLElement($url, null, true);

echo "totalResultsCount: " . $xml->totalResultsCount . "<br />";

foreach($xml->geoname as $geoname) {
    echo $geoname->toponymName . "<br />";
    echo $geoname->lat . "<br />";
    echo $geoname->countryCode . "<br />";
    echo $geoname->countryName . "<br />";
    echo $geoname->adminName1 . "<br />";
    echo $geoname->adminName2 . "<br />";
}

which displays the results as follows:

totalResultsCount: 225
Glacier Bay National Park and Preserve
58.50056
US
United States
Alaska
US.AK.232

...
+2
source

First of all, it seems like the web service is returning XML, not JSON. You can use SimpleXML to parse this.

Secondly, you can check curl

Example:

$ch = curl_init("http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK");

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$content = curl_exec($ch); 

curl_close($ch);
+1
source

fopen , . json-, . - file_get_contents.

$query = 'http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK';
$response = file_get_contents($query);
// You really should do error handling on the response here.
$decoded = json_decode($response, true);
echo '<p>Decoded: '.$decoded['lat'].'</p>';
+1

All Articles