使用 cURL 返回 API XML 响应



如果这很简单,请原谅我。我的研究使我此刻停滞不前。我正在尝试使用 cURL 来获取 XML 格式 API 的响应。

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

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

这是 API 的文档。在 API 参考选项卡下是状态,我只需要将请求标头更改为应用程序/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);
?>

我刚刚尝试了您的代码,它适用于 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

最新更新