PHP REST API 使用 cURL更新数据

在本教程中,我们将学习如何使用 HTTP PUT 使用 cURL 函数更新 REST API 数据。

通过 PUT 方法发送的 SAMPLE REST API 数据

我们将使用 Dummy REST API 示例网站来处理 HTTP PUT 方法和员工记录。

创建新员工的 API URL:http://dummy.restapiexample.com/api/v1/update/10

要更新员工,我们需要在 URL 中传递该员工的 ID,并以以下 JSON 格式传递更新的详细信息。
我们将使用 cURL 来发送这些数据。

[{"id":"110","employee_name":"Robin Ma","employee_salary":"7270","employee_age":"34"}]

PHP 程序通过 cURL 使用 PUT REST API 命令更新用户数据

在下面的 PHP 程序中,我们将使用 id '10' 更新用户。
此数据将使用 cURL 中的 HTTP POST 方法传递到给定的 URL 并创建一个新用户。

<?php

// 在curl中使用HTTP PUT方法发送的用户数据
$data = array('name'=>'New Robin User','salary'=>'62000', 'age' => '34');

// 以json格式发送数据
$data_json = json_encode($data);

// 更新URL
$url = 'http://dummy.restapiexample.com/api/v1/update/10';

// curl初始化
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));

// 设置PUT方法
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

// 设置发送的数据
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 执行 curl 
$response  = curl_exec($ch);

// 关闭 curl
curl_close($ch);

// 检查返回结果,查看是否成功
print_r ($response);

?>
日期:2020-09-17 00:10:24 来源:oir作者:oir