使用PHP接收JSON POST数据

以下示例显示了如何使用PHP获取或者获取JSON Post数据。

  • 使用json_decode()函数在PHP中解码JSON数据。
  • file_get_contents()函数用于以更可读的格式接收数据。
$data = json_decode(file_get_contents('php://input'), true);

通过post使用php curl发送JSON数据

以下示例使HTTP POST请求进行HTTP POST请求,并将JSON数据发送到PHP中的CURL。

  • 指定要发送的JSON数据的URL('$url')。
  • 使用curl_init()启动新的curl资源。
  • 使用json_encode()在PHP数组中设置数据并将其编码为JSON字符串。
  • 使用curlopt_postfields选项将JSON数据添加到POST字段。
  • 使用curlopt_httpheader选项将请求的内容类型设置为“应用程序/json”。
  • 将响应作为字符串返回,而不是使用curlopt_returntransfer选项输出它。
  • 最后,CURL_EXEC()函数用于执行POST请求。
//API URL
$url = 'http://www.example.com/api';
//Create a new cURL resource
$ch = curl_init($url);
//Setup request to send json via POST
$data = array(
    'username' => 'onitroad',
    'password' => '123456'
);
$payload = json_encode(array("user" => $data));
//Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
//Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the POST request
$result = curl_exec($ch);
//Close cURL resource
curl_close($ch);
如何使用PHP CURL发送和接收JSON数据

JSON是用于在浏览器和服务器之间交换数据的最流行的数据格式。
JSON数据格式主要用于Web服务以通过API互换数据。
使用Web服务和API时,通过POST请求发送JSON数据是最需要的功能。
PHP CURL使JSON数据将JSON数据发布到URL。
在本教程中,我们将展示如何使用PHP Curl发布JSON数据并在PHP中获取JSON数据。

日期:2020-06-02 22:15:58 来源:oir作者:oir