我正在PHP中創建一個API端點,並且有一個輸出JSON的頁面,我們稱之爲example.com/stats
。當用戶試圖返回數據時,只有在使用file_get_contents()
時纔會成功,當用戶嘗試使用cURL訪問數據時,它們會收到NULL響應。我應該如何在PHP中提供JSON數據,以便與file_get_contents和curl兼容?頁面可由file_get_contents讀取,但不能捲曲
更多信息如下。
源/統計
header('Content-type: application/json');
echo '{"status":"error", "message":"invalid operation"}';
當我嘗試通過file_get_contents()
一切正常,從另一個服務器讀取這個頁面。
function fgc($receive_url){
$fgc = json_decode(file_get_contents($receive_url), true);
return $fgc;
}
$out = fgc("https://example.com/stats");
var_dump($out);
//returns: array(2) { ["status"]=> string(5) "error" ["message"]=> string(17) "invalid operation" }
當我嘗試做同樣的事情,但與捲曲我得到NULL
。
function curlit($receive_url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
return $json;
}
$out = curlit("https://example.com/stats");
var_dump($out);
請注意,我的捲曲功能顯示JSON做工精細的其他網站,它是專門我從example.com/stats
使用捲曲時無法提供數據服務。我認爲使用頭文件application/json足以讓這個數據可以通過cURL到達。任何想法在服務方面可能是錯誤的?爲什麼文件會獲得內容但不捲曲?也許cURL在頁面加載完成之前顯示結果?我嘗試刪除應用程序/ JSON標題,但沒有任何區別。
它是HTTP或HTTPS URL? – theomessin
HTTPS。 'example.com'上的SSL處於活動狀態並通過cloudflare啓用。 – m1xolyd1an
你可以嘗試使用cURL的CLI版本,看看是否有效? – theomessin