PHP 如何点击网址并下载其 xml


PHP How to hit a url and download its xml

我正在尝试发送此查询:

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

到 Web 服务并在那里下拉并解析一堆字段,即这些字段:

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

我正在这样做:

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

有人可以提供正确的代码来循环结果并获取值吗?

由于响应是XML,因此可以使用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 />";
}

这将显示如下结果:

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

首先,看起来 Web 服务返回的是 XML 而不是 JSON。 您可以使用 SimpleXML 来解析它。

其次,你可能想看看卷曲

举个例子:

$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);

>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>';