How do I send a POST request with PHP?

前端 未结 13 1870
暗喜
暗喜 2020-11-21 05:40

Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not t

13条回答
  •  孤城傲影
    2020-11-21 05:53

    There's another CURL method if you are going that way.

    This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.

    $url = 'http://api.example.com/services/xmlrpc/';
    $ch = curl_init($url);
    
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    //process $response
    

    First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.

提交回复
热议问题