POST XML to URL with PHP and Handle Response

后端 未结 5 955
天命终不由人
天命终不由人 2020-12-11 11:16

I\'ve seen numerous methods of POSTing data with PHP over the years, but I\'m curious what the suggested method is, assuming there is one. Or perhaps there is a somewhat uns

相关标签:
5条回答
  • 2020-12-11 12:01

    There isn't really a standard way. In code meant for distribution, I generally check cURL, file_get_contents and sockets, using the first one found. Each of those supports GET and POST, and each of those may or may not be available (or work) depending on the PHP version and configuration.

    Basically something like:

    function do_post($url, $data) {
      if (function_exists('curl_init') && ($curl = curl_init($url))) {
        return do_curl_post($curl, $data);
      } else if (function_exists('file_get_contents') && ini_get('allow_url_fopen') == "1") {
        return do_file_get_contents_post($url, $data);
      } else {
        return do_socket_post($url, $data);
      }
    }
    
    0 讨论(0)
  • 2020-12-11 12:02

    cURL is the only reliable way I know of, to POST data, aside from using a socket.

    Now if you wanted to send data via GET there are several methods:
    cURL
    sockets
    file_get_contents
    file
    and others

    0 讨论(0)
  • 2020-12-11 12:05

    You could try the Snoopy script
    It is useful on hosting providers that don't allow fopen wrappers
    I have used it for several years to grab RSS feeds.

    0 讨论(0)
  • 2020-12-11 12:09

    While the Snoopy script maybe cool, if you're looking to just post xml data with PHP, why not use cURL? It's easy, has error handling, and is a useful tool already in your bag. Below is an example of how to post XML to a URL with cURL in PHP.

    // url you're posting to        
    $url = "http://mycoolapi.com/service/";
    
    // your data (post string)
    $post_data = "first_var=1&second_var=2&third_var=3";
    
    // create your curl handler     
    $ch = curl_init($url);
    
    // set your options     
    curl_setopt($ch, CURLOPT_MUTE, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //ssl stuff
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:  application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    // your return response
    $output = curl_exec($ch); 
    
    // close the curl handler
    curl_close($ch);
    
    0 讨论(0)
  • 2020-12-11 12:11

    I like Zend_Http_Client from Zend Framework.

    It basically works using stream_context_create() and stream_socket_client().

    Small example:

    $client = new Zend_Http_Client();
    $client->setUri('http://example.org');
    $client->setParameterPost('foo', 'bar')
    $response = $client->request('POST');
    
    $status = $response->getStatus();
    $body = $response->getBody();
    
    0 讨论(0)
提交回复
热议问题