使用PHP和处理响应将XML发布到URL

时间:2009-01-23 01:18:01

标签: php xml api post

多年来我见过很多用PHP发布数据的方法,但我很好奇建议的方法是什么,假设有一个方法。或者也许有一种有些未说出口但半普遍接受的方法。这也包括处理响应。

5 个答案:

答案 0 :(得分:3)

虽然史努比脚本可能很酷,但如果您希望使用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);

答案 1 :(得分:1)

除了使用cURL之外,

socket是我所知道的唯一可靠的POST数据方式。

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

我喜欢Zend_Http_Client中的Zend Framework

它基本上可以使用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();

答案 4 :(得分:0)

没有真正的标准方式。在用于分发的代码中,我通常使用找到的第一个代码检查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);
  }
}
相关问题