优秀的编程知识分享平台

网站首页 > 技术文章 正文

PHP 使用 curl POST提交 json 格式数据

nanyue 2024-10-03 23:36:18 技术文章 5 ℃
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);//提交的JSON数据
 $ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");//POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
 $result = curl_exec($ch);

PHP模拟提交POST,数据为JSON数据的源代码

这个POST请求可以扩展带COOKIE进行请求,现在大多数网站都的请求方式都变成这一种了,通过这段代码可解决大部分网站请求问题。

欢迎大家评论区交流!

最近发表
标签列表