共計 604 個字符,預計需要花費 2 分鐘才能閱讀完成。
要使用 PHP 從 API 獲取數據,你需要使用 PHP 的內置函數 file_get_contents()
或者 curl
來發送 HTTP 請求,并解析返回的 JSON 數據。
以下是一個簡單的示例:
// API 的 URL
$url = 'https://api.example.com/data';
// 使用 file_get_contents()發送 HTTP 請求并獲取數據
$response = file_get_contents($url);
// 解析 JSON 數據
$data = json_decode($response, true);
// 輸出數據
print_r($data);
如果你希望使用 curl
發送 HTTP 請求,可以使用以下示例:
// 初始化一個 cURL 會話
$ch = curl_init();
// 設置 cURL 選項
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 執行 cURL 請求并獲取數據
$response = curl_exec($ch);
// 關閉 cURL 會話
curl_close($ch);
// 解析 JSON 數據
$data = json_decode($response, true);
// 輸出數據
print_r($data);
記得替換示例中的 API URL 為你要獲取數據的 API 的實際 URL。
丸趣 TV 網 – 提供最優質的資源集合!
正文完