📜  php curl post json - PHP (1)

📅  最后修改于: 2023-12-03 14:45:10.681000             🧑  作者: Mango

PHP curl post json

在使用API时,常常需要向服务端发送JSON数据,本文将介绍如何使用PHP中的CURL库发送POST请求并发送JSON数据,用于实现与其他服务器的交互。

前置知识
  1. 熟悉PHP语言本身的语法基础知识。
  2. 了解HTTP协议、RESTful API的基本知识。
  3. 熟悉JSON格式的基本语法。
简介

PHP提供了CURL库,可以很方便地与其他服务器交互,实现客户端与服务端的通信。下面是使用CURL发送POST请求的基本代码:

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
   CURLOPT_URL => "http://example.com",
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_ENCODING => "",
   CURLOPT_MAXREDIRS => 10,
   CURLOPT_TIMEOUT => 30,
   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_CUSTOMREQUEST => "POST",
   CURLOPT_POSTFIELDS => "var1=value1&var2=value2",
   CURLOPT_HTTPHEADER => array(
      "cache-control: no-cache",
      "content-type: application/x-www-form-urlencoded"
   ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
   echo "cURL Error #:" . $err;
} else {
   echo $response;
}
?>
发送JSON数据

如果要发送JSON数据,则需要设置CURLOPT_POSTFIELDS为一个JSON字符串。下面是实现的基本代码:

<?php
$data = [
    "name" => "John Doe",
    "age" => 30,
    "email" => "johndoe@example.com"
];

$data_string = json_encode($data);

$curl = curl_init();

curl_setopt_array($curl, array(
   CURLOPT_URL => "http://example.com",
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_ENCODING => "",
   CURLOPT_MAXREDIRS => 10,
   CURLOPT_TIMEOUT => 30,
   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_CUSTOMREQUEST => "POST",
   CURLOPT_POSTFIELDS => $data_string,
   CURLOPT_HTTPHEADER => array(
      "cache-control: no-cache",
      "content-type: application/json"
   ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
   echo "cURL Error #:" . $err;
} else {
   echo $response;
}
?>

可以看到,这里将提交的数据 $data 转化为了 $data_string JSON字符串,然后将它作为CURLOPT_POSTFIELDS的值发送。同时,请求头中的Content-type也需要设置为application/json,这样服务端才能正确解析JSON数据。

总结

本文讲解了使用PHP中的CURL扩展库向服务端发送JSON数据的方法。通过设置CURLOPT_POSTFIELDS为JSON字符串,并设置正确的请求头Content-Type,即可实现向服务端发送JSON数据。