如何使用 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