在本教程中,我们将学习如何使用 PHP 中的 cURL 函数删除一些 REST API 数据。
使用 cURL 删除数据的 SAMPLE REST API
我们将使用 Dummy REST API 示例网站使用 cURL 来处理 HTTP DELETE 方法。
删除员工的 API URL:http://dummy.restapiexample.com/api/v1/delete/17
在这个 API URL(也称为路由或者端点)中,我们将使用特定的员工 ID 来删除他的记录。
请使用 '/delete/' 而不是 '/update/' 。
使用 cURL 删除 REST API 数据的 PHP 程序
在下面的 PHP 程序中,我们将删除一个 ID 为“19465”的员工。
如果用户存在,则将其删除并收到成功响应。
我们需要确保传递实际存在的员工 ID。
<?php
// 在curl中使用HTTP POST方法发送的用户数据
$data = array();
//数据应以json格式传递
$data_json = json_encode($data);
// 发送数据的API URL
$url = 'http://dummy.restapiexample.com/api/v1/delete/19465';
// curl 初始化
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
// 将json头正确设置为接收到的json响应
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
// 将方法设置为 DELETE
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "DELETE");
// 设置发送的数据
curl_setopt($curl_handle, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
// 执行 curl
$response = curl_exec($curl_handle);
// 关闭 curl
curl_close($curl_handle);
// 查看结果
print_r ($response);
?>
日期:2020-09-17 00:10:23 来源:oir作者:oir
