使用cURL返回API XML响应

问题描述:

如果这很简单,请原谅我。我的研究目前使我停下脚步。我正在尝试使用cURL来获取XML中的API响应。使用cURL返回API XML响应

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

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

这是API的文档。在“API参考”选项卡下,我只需要将请求标头更改为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); 

?> 

我只是想你的代码,它工作正常原子:

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

“应用/帽+ XML”不适用于网址的方式,就像你在一个问题中提到,虽然。

每商务部https://alerts-v2.weather.gov/documentation的格式如下:

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

感谢您的答复。我用atom + xml试过了,我还没有收到任何东西只是一个空白的白页。这只是在5月份更新,因此它不是过时的,因为它是刚刚发布的新API。以下是来自其页面的XML响应示例。 https://alerts-v2.weather.gov/products/active?region_type=land – Texan78

+0

啊我错过了echo声明。我现在得到了一个响应,但是当我在cap + xml中请求它时,它会以JSON的形式返回它。 – Texan78

+0

是的,我明白,但ATOM是他们试图摆脱的东西。这是2017年5月的新API,因此cap + xml被维护。这是一个例子。此外,如果您从那里点击XML,它将使用cap + xml向您显示响应的预览,因此它被维护得非常好。 https://alerts-v2.weather.gov/products/active?region_type=land – Texan78