Linux 拨号vps windows公众号手机端

php怎么设置http请求体

lewis 7年前 (2018-11-17) 阅读数 13 #程序编程
文章标签 PHP

在PHP中,可以使用以下两种方法设置HTTP请求体:

  1. 使用file_get_contents()函数发送POST请求,并设置请求体数据。
$url = 'http://example.com/api';
$data = array('name' => 'John', 'age' => 30);
$options = array(
'http' => array(
'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
'method'  => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
  1. 使用cURL库发送POST请求,并设置请求体数据。
$url = 'http://example.com/api';
$data = array('name' => 'John', 'age' => 30);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result = curl_exec($ch);
curl_close($ch);

注意:以上示例中的$data数组为请求体数据,可以根据需要进行修改。http_build_query()函数用于将数组转换为URL编码的字符串。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门