php模拟post提交json数据,如何在PHP中利用curl模拟post提交json数据

如何在PHP中利用curl模拟post提交json数据

发布时间:2021-02-05 16:30:19

来源:亿速云

阅读:63

作者:Leah

本篇文章为大家展示了如何在PHP中利用curl模拟post提交json数据,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。<?php

header("Content-type:application/json;charset=utf-8");

$url="http://192.168.10.234:8080/uc/login/loginid";

$param=array(

//注册字段

"name"=>"test001",

"pass"=>"xxxx",

);

$data = json_encode($param);

list($return_code, $return_content) = http_post_data($url, $data);//return_code是http状态码

print_r($return_content);exit;

function http_post_data($url, $data_string) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

"Content-Type: application/json; charset=utf-8",

"Content-Length: " . strlen($data_string))

);

ob_start();

curl_exec($ch);

$return_content = ob_get_contents();

ob_end_clean();

$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

return array($return_code, $return_content);

}

上述内容就是如何在PHP中利用curl模拟post提交json数据,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP模拟POST JSON数据可以通过使用cURL库来实现。 首先,我们需要设置POST请求的URL和要发送的JSON数据。可以使用`json_encode()`函数将关联数组转换为JSON字符串。例如: ```php $url = "http://example.com/api"; $data = array( "name" => "John Doe", "email" => "[email protected]" ); $jsonData = json_encode($data); ``` 然后,我们需要使用cURL库来发送POST请求。可以使用`curl_init()`函数初始化一个cURL会话,并通过`curl_setopt()`函数设置相关选项。例如,设置`CURLOPT_URL`选项为要发送的URL,设置`CURLOPT_RETURNTRANSER`为true以获取返回的响应。为了发送JSON数据,我们还需要将`CURLOPT_HTTPHEADER`选项设置为`"Content-Type: application/json"`。最后,通过`curl_exec()`函数执行cURL会话并获取相应: ```php $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData); $response = curl_exec($curl); curl_close($curl); ``` 最后,我们可以通过解析返回的响应来获取服务器返回的结果。可以使用`json_decode()`函数将JSON字符串转换为关联数组。例如: ```php $result = json_decode($response, true); echo $result["status"]; ``` 以上就是使用PHP模拟POST JSON的基本步骤。通过设置相关的选项,我们可以对请求进行更多的定制,例如设置请求头、设置超时时间等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值