在PHP中,可以使用以下兩種方法設置HTTP請求體:
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);
$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編碼的字符串。