我需要像这样放一个数据字符串:'<使用PHP将client>…<'client>'连接到XMl服务器(例如url:'http://example.appspot.com/examples')。(上下文:向服务器添加新客户端的详细信息)。使用PHP将client>
我已经尝试使用CURLOPT_PUT,一个文件,只是一个字符串(因为它需要CURLOPT_INFILESIZE和CURLOPT_INFILE),但它不工作!
是否有其他PHP函数可以用来做这样的事情?我一直在寻找,但PUT请求信息是稀疏的。
谢谢。
// Start curl
$ch = curl_init();
// URL for curl
$url = "http://example.appspot.com/examples";
// Put string into a temporary file
$putString = '<client>the RAW data string I want to send</client>';
/** use a max of 256KB of RAM before going to disk */
$putData = fopen('php://temp/maxmemory:256000', 'w');
if (!$putData) {
die('could not open temp memory data');
}
fwrite($putData, $putString);
fseek($putData, 0);
// Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Binary transfer i.e. --data-BINARY
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
// Using a PUT method i.e. -XPUT
curl_setopt($ch, CURLOPT_PUT, true);
// Instead of POST fields use these settings
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
$output = curl_exec($ch);
echo $output;
// Close the file
fclose($putData);
// Stop curl
curl_close($ch);
因为到目前为止我还没有使用过cURL,所以我不能真正回答这个话题。如果你想使用cURL,我建议查看服务器日志,看看到底是什么不起作用(所以:请求的输出真的是它应该是什么吗?)
如果你不介意切换到另一个技术/库,我建议你使用Zend HTTP客户端,它真的很容易使用,很容易包含,应该满足你所有的需求。特别是当执行PUT请求就像这样简单时:
<?php
// of course, perform require('Zend/...') and
// $client = new Zend_HTTP_Client() stuff before
// ...
[...]
$xml = '<yourxmlstuffhere>.....</...>';
$client->setRawData($xml)->setEncType('text/xml')->request('PUT');
?>
代码示例来自:Zend Framework Docs # RAW-Data Requests
在PHP中使用CURL向PUT请求添加字符串主体的另一种方法是:
<?php
$data = 'My string';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // Define method type
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Set data to the body request
?>
我希望这对你有帮助!