2017-08-12 122 views
1

如果這很簡單,請原諒我。我的研究目前使我停下腳步。我正在嘗試使用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); 

?> 

回答

0

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

$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