duanfenhui5511 2016-09-11 17:14
浏览 63

在cURL请求上强制XML输出

I am using a cURL request to get XML data, which works fine in the brower but returns text in the PHP cURL. I have looked at several similar questions here and tried the answers, with no luck. Here's the code.

$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);
  • 写回答

1条回答 默认 最新

  • dongshanxiao7328 2016-09-16 07:43
    关注

    Your request already contains FcstType parameter to specify that response should be returned in XML format: FcstType=xml

    Once XML response (string) is returned it could be parsed with SimpleXMLElement class as demonstrated below:

    $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 . "
    ";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料