我正在使用cURL请求来获取XML数据,这在浏览器中工作正常,但在PHP cURL中返回文本。我在这里看了几个类似的问题并尝试了答案,没有运气。这是代码。
$url = 'http://forecast.weather.gov/MapClick.phplat=38.4247341&lon=-86.9624086&FcstType=xml';
$agent = 'Myapp/v1.0 (http://example.org;webmaster@example.org)';
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_URL, $url);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($rCURL, CURLOPT_USERAGENT, $agent);
curl_setopt($rCURL, CURLOPT_HTTPHEADER, 'Content-Type: application/xml');
curl_setopt($rCURL, CURLOPT_BINARYTRANSFER, 1);
$aData = curl_exec($rCURL);
$error = curl_error($CURL);
curl_close($rCURL);
if ($error)
echo ($error);
else echo ($aData);
答案 0 :(得分:0)
您的请求已包含FcstType
参数,以指定应以XML格式返回响应:FcstType=xml
返回XML响应(字符串)后,可以使用SimpleXMLElement class
进行解析,如下所示:
$url = 'http://forecast.weather.gov/MapClick.php?lat=38.4247341&lon=-86.9624086&FcstType=xml';
$agent = 'Myapp/v1.0 (http://example.org;webmaster@example.org)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($response);
foreach($xml->period as $period){
echo $period->text . "\n";
}