猿问

如何用PHP发送POST请求?

如何用PHP发送POST请求?

实际上,我想阅读搜索查询完成后的内容。问题是URL只接受POST方法,并且它不采取任何与GET方法.。

我必须在以下的帮助下阅读所有的内容domdocumentfile_get_contents()..有什么方法可以让我用POST方法,然后通过PHP?


四季花海
浏览 1419回答 3
3回答

烙印99

你可以用卷发:<?php//The url you wish to send the POST request to$url = $file_name;//The data you want to send via POST$fields = [&nbsp; &nbsp; '__VIEWSTATE '&nbsp; &nbsp; &nbsp; => $state,&nbsp; &nbsp; '__EVENTVALIDATION' => $valid,&nbsp; &nbsp; 'btnSubmit'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;=> 'Submit'];//url-ify the data for the POST$fields_string = http_build_query($fields);//open connection$ch = curl_init();//set the url, number of POST vars, POST datacurl_setopt($ch,CURLOPT_URL, $url);curl_setopt($ch,CURLOPT_POST, true);curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);//So that curl_exec returns the contents of the cURL; rather than echoing itcurl_setopt($ch,CURLOPT_RETURNTRANSFER, true);&nbsp;//execute post$result = curl_exec($ch);echo $result;?>

牛魔王的故事

我使用以下函数使用curl发布数据。$data是要发布的字段数组(将使用http_build_query正确编码)。数据是使用application/x-www-form-urlencode编码的。function&nbsp;httpPost($url,&nbsp;$data){ &nbsp;&nbsp;&nbsp;&nbsp;$curl&nbsp;=&nbsp;curl_init($url); &nbsp;&nbsp;&nbsp;&nbsp;curl_setopt($curl,&nbsp;CURLOPT_POST,&nbsp;true); &nbsp;&nbsp;&nbsp;&nbsp;curl_setopt($curl,&nbsp;CURLOPT_POSTFIELDS,&nbsp;http_build_query($data)); &nbsp;&nbsp;&nbsp;&nbsp;curl_setopt($curl,&nbsp;CURLOPT_RETURNTRANSFER,&nbsp;true); &nbsp;&nbsp;&nbsp;&nbsp;$response&nbsp;=&nbsp;curl_exec($curl); &nbsp;&nbsp;&nbsp;&nbsp;curl_close($curl); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;$response;}@Edward提到,可以省略http_Build_Query,因为curl将正确地编码传递给CURLOPT_POSTFIES参数的数组,但请注意,在这种情况下,数据将使用多部分/表单-数据进行编码。我在API中使用这个函数,这些API期望使用application/x-www-form-urlencode对数据进行编码。这就是为什么我使用http_build_query()。
随时随地看视频慕课网APP
我要回答