【发布时间】:2011-08-14 18:47:17
【问题描述】:
我需要使用 PHP 将这样的数据字符串:'
我尝试过使用 CURLOPT_PUT,带有一个文件和一个字符串(因为它需要 CURLOPT_INFILESIZE 和 CURLOPT_INFILE),但它不起作用!
还有其他 PHP 函数可以用来做这样的事情吗?我一直在环顾四周,但 PUT 请求信息很少。
谢谢。
【问题讨论】:
我需要使用 PHP 将这样的数据字符串:'
我尝试过使用 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 Client,它使用起来非常简单,包含简单,应该可以满足您的所有需求。尤其是执行 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');
?>
【讨论】:
在 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
?>
我希望这会有所帮助!
【讨论】: