【问题标题】:POST XML to URL with PHP and Handle Response使用 PHP 将 XML 发布到 URL 并处理响应
【发布时间】:2010-10-03 01:24:48
【问题描述】:

多年来,我已经看到了许多使用 PHP 发布数据的方法,但我很好奇建议的方法是什么,假设有一个。或者也许有一种不言而喻但半普遍接受的方法。这也包括处理响应。

【问题讨论】:

    标签: php xml api post


    【解决方案1】:

    虽然 Snoopy 脚本可能很酷,但如果您希望只使用 PHP 发布 xml 数据,为什么不使用 cURL?它很简单,具有错误处理功能,并且是您包中已有的有用工具。下面是一个示例,说明如何在 PHP 中使用 cURL 将 XML 发布到 URL。

    // 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);
    

    【讨论】:

    • 那不是xml……那是nvp
    【解决方案2】:

    你可以试试Snoopy script
    它对不允许fopen wrappers的托管服务提供商很有用
    我已经使用它几年来获取 RSS 提要。

    【讨论】:

    • 哇。我刚刚看了史努比脚本,它非常简单。我一定会看看这个。
    • 我认为它甚至包含在一些较大的开源 PHP 项目中。
    • Zend_Http_Client 也是一个好主意。如果您要使用 Zend 框架的其他部分,我会使用它。
    • @Bruno,我目前没有使用 Zend,将来也不打算使用。不过,我确实计划使用 CodeIgniter,因此我也可能会在该社区中搜索潜在的解决方案。
    • 然后我会倾向于史努比,并为您的需要编写一个小的抽象或服务层。这样你的代码依赖于你的服务层而不是史努比。以后可以换掉它。
    【解决方案3】:

    cURL 是我所知道的唯一可靠的 POST 数据方式,除了使用 socket

    现在,如果您想通过 GET 发送数据,有几种方法:
    cURL
    sockets
    file_get_contents
    file
    和其他人

    【讨论】:

      【解决方案4】:

      我喜欢来自Zend FrameworkZend_Http_Client

      它基本上可以使用stream_context_create()stream_socket_client()

      小例子:

      $client = new Zend_Http_Client();
      $client->setUri('http://example.org');
      $client->setParameterPost('foo', 'bar')
      $response = $client->request('POST');
      
      $status = $response->getStatus();
      $body = $response->getBody();
      

      【讨论】:

        【解决方案5】:

        没有真正的标准方法。在用于分发的代码中,我通常使用找到的第一个来检查cURLfile_get_contentssockets。其中每一个都支持 GET 和 POST,根据 PHP 版本和配置,每一个都可能可用或不可用(或工作)。

        基本上是这样的:

        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);
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-11-12
          • 2015-04-06
          • 2018-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-02
          相关资源
          最近更新 更多