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 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名