如何使用 Curl 和 PHP 传递 JSON 数据以进行 PUT、POST、GET 和 DELETE
利用 Curl 和 PHP 进行 CRUD 操作REST API 是一种便捷的方法。虽然命令行提供了传递 JSON 数据的简单方法,但 PHP 需要自定义实现。
PUT 的 PHP Curl 实现:
<?php $data = array('username' => 'dog', 'password' => 'tall'); $data_json = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_json))); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
PHP Curl POST 的实现:
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
PHP Curl 实现GET(替代方法):
<?php $query_string = http_build_query($data); $url = $url . '?' . $query_string; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
删除的 PHP Curl 实现:
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
以上是如何使用Curl和PHP发送JSON数据进行REST API CRUD操作?的详细内容。更多信息请关注PHP中文网其他相关文章!