【问题标题】:Using cURL to return API XML response使用 cURL 返回 API XML 响应
【发布时间】:2017-08-12 19:17:52
【问题描述】:

如果这很简单,请原谅我。我的研究让我暂时停了下来。我正在尝试使用 cURL 来获取 XML 中 API 的响应。

这是 API 的 URL:https://api.weather.gov/alerts/active/region/land

默认情况下它以 JSON 格式返回。我知道,我应该只使用 JSON 响应,但是,我需要它在 XML 中是有原因的,因为它将无缝集成到我当前的代码中,直到我可以将它重写为 JSON。

这是 API 的文档。在 API Reference 选项卡下是状态,我只需要将请求标头更改为 application/cap+xml。但我没有得到任何回报。只是一张空白的白页。

https://alerts-v2.weather.gov/documentation

这是我当前用来调用 API 的代码,但我没有得到任何响应或任何东西。我错过了什么?

    <?php

     $headers[] = 'Connection: Keep-Alive';
     $headers[] = 'Content-Type: application/cap+xml;charset=utf-8';
     $headers[] = 'Accept: application/cap+xml';

     $userAgent = 'php';

     $url = 'https://api.weather.gov/alerts/active/region/land';

     $cURL = curl_init();

     curl_setopt($cURL, CURLOPT_URL, $url);
     curl_setopt($cURL, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($cURL, CURLOPT_USERAGENT, $userAgent);
     curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($cURL, CURLOPT_HTTPGET, true);

     $result = curl_exec($cURL);

     curl_close($cURL);

?>

【问题讨论】:

    标签: php xml curl


    【解决方案1】:

    我刚刚尝试了你的代码,它在 atom 上运行良好:

    $headers[] = 'Accept: application/atom+xml';
    

    "application/cap+xml" 不适用于 URL,就像您在问题中提到的那样。

    根据文档https://alerts-v2.weather.gov/documentation,格式如下:

    /alerts/active/region/{region} => JSON-LD (default), ATOM 
    /alerts/{alertId}   => JSON-LD (default), CAP
    

    【讨论】:

    • 感谢您的回复。我用 atom+xml 试过了,但我什么也没得到,只是一个空白的白页。这只是在 5 月更新,所以它没有过时,因为它是他们刚刚发布的新 API。这是来自他们页面的 XML 响应的示例。 alerts-v2.weather.gov/products/active?region_type=land
    • 啊,我错过了 echo 语句。我现在收到了响应,但是当我在 cap+xml 中请求它时,它会以 JSON 格式返回它。
    • 是的,我明白,但是,ATOM 是他们试图摆脱的东西。这是 2017 年 5 月的新 API,因此 cap+xml 得到维护。这是一个例子。此外,如果您从那里单击 XML,它将使用 cap+xml 向您显示响应的预览,因此它得到了很好的维护。 alerts-v2.weather.gov/products/active?region_type=land
    • 归根结底,问题是由于 2 个派系。我错过了回声声明。此外,我想做的事情在 CAP 中也没有。所以需要硬着头皮尽快切换到 JSON。
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多