我想向API发送一个put请求,希望将请求的详细信息作为XML
显然我需要在使用PUT和PHP时将xml作为文件发送。
我该怎么做?
以下是我正在尝试的内容:
$HttpSocket = new HttpSocket();
$result = $HttpSocket->put($put, $fh);
其中$ put是url,而$ fh是我在飞行中制作的文件,如此
$xmlObject = Xml::fromArray($xmlArray);
$xmlString = $xmlObject->asXML();
$fh = fopen('php://memory', 'rw');
fwrite($fh, $xmlString);
rewind($fh);
答案 0 :(得分:3)
我在蛋糕2.0.5上测试了它,HttpSocket :: put可以发送键值数组或原始字符串作为postdata。
因此,您可以直接发送xml字符串,远程服务器将在Raw Post Data i中读取它。即file_get_contents("php://input")
这有效:
$http = new HttpSocket();
$xml_data = Xml::fromArray($data);
$xml_string = $xml_data->asXML();
$response = $http->put('http://example.com', $xml_string);
为了演示它,我创建了一个名为RequestXmlTestController的Controller,其归档于'Controllers/RequestXmlTestController.php'
(代码如下),以及'RequestXmlTests/index.ctp'
控制器代码:
<?php
App::uses('AppController', 'Controller');
/**
* RequestXmlTest Controller
*
*/
class RequestXmlTestController extends AppController {
/**
* Use no Model
*/
public $uses = array();
/**
* index action
*/
public function index(){
App::uses('HttpSocket', 'Network/Http');
App::uses('Xml', 'Utility');
$http = new HttpSocket();
$data = array(
'type' => array('name' => 'Campaign', 'data' => array(
array('name' => 'Come eat at Joe\'s', 'products' => array('adserver', 'analytics'))
))
);
$xml_data = Xml::fromArray($data);
$xml_string = $xml_data->asXML();
$response = $http->put(Router::url(array('action' => 'test'), true), $xml_string);
debug($response);
}
/**
* test action
* Test the requests and dump Raw Post Data and Cake's Request object
*/
public function test(){
var_dump(array('raw_post_data' => file_get_contents("php://input")));
echo "\n\n";
var_dump($this->request);
exit;
$this->render('index');
}
}
参考文献: HttpSocket Documentation
答案 1 :(得分:0)
我最后只是使用php而不是php助手
# write data into a temporary file
$putData = "<subscription><productPath>$new_product_path</productPath></subscription>";
$putDataFile = tmpfile();
fwrite($putDataFile, "<subscription><productPath>$new_product_path</productPath></subscription>");
fseek($putDataFile, 0);
# initialize PUT call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.example.com");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/xml"));
curl_setopt($ch, CURLOPT_INFILE, $putDataFile);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
# executes PUT call and clean up
$result = curl_exec($ch);
$info = curl_getinfo($ch);
fclose($putDataFile);
curl_close($ch);
我更喜欢使用Cake类来实现整洁,但这适用于我使用的api。