如何使用 cURL 在 PHP 中獲取 JSON 資料和解碼 JSON 資料
Minahil Noor
2020年6月25日
PHP
PHP cURL
PHP JSON
在本文中,我們將介紹在 PHP 中使用 cURL 獲取 JSON 資料和解碼 JSON 資料的方法。
- 使用
cURL函式
在 PHP 中使用 cURL 函式獲取 JSON 資料並解碼 JSON 資料
cURL 有不同的函式,它們共同用於獲取 JSON 資料和解碼 JSON 資料。它們是 curl_init(),curl_setopt(),curl_exec() 和 curl_close()。這些函式的細節如下
函式 curl_init() 用於初始化使用 cURL 函式的新會話。使用此函式的正確語法如下
curl_init($url);
引數 $url 是可選引數。如果提供,則其值設定為 CURLOPT_URL。如果不是,那麼我們可以稍後進行設定。成功後,此函式將返回 cURL 控制代碼。
函式 curl_setopt() 用於設定 cURL 程序的選項。使用此函式的正確語法如下
curl_setopt($handle, $option, $value);
第一個引數是 curl_init() 函式返回的控制代碼。第二個引數是 cURL 程序的選項。第三個引數是所選選項的值。你可以在此處檢查選項。
函式 curl_exec() 執行 cURL 會話。成功返回 true,失敗返回 false。使用此函式的正確語法如下。
curl_exec($handle);
它只有一個引數 $handle,即 curl_init() 函式返回的控制代碼。
函式 curl_close() 關閉由 curl_init() 函式初始化的會話。使用此函式的正確語法如下
curl_close($handle);
它只接受一個引數 $handle,即 curl_init() 函式返回的控制代碼。
現在,我們將使用這些函式獲取 JSON 資料並解碼 JSON 資料。
// Initiate curl session
$handle = curl_init();
// Will return the response, if false it prints the response
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($handle, CURLOPT_URL,$YourUrl);
// Execute the session and store the contents in $result
$result=curl_exec($handle);
// Closing the session
curl_close($handle);
現在我們將使用 file_get_contents() 函式從 URL 獲取 JSON 資料,並使用 json_decode() 函式將 JSON 字串轉換為陣列。
$result = file_get_contents($url);
$array = json_decode($result, true);
var_dump($array);
函式 var_dump() 將以陣列形式顯示 JSON 資料。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe