我编写了一个PHP脚本,将XML发布到我的服务器:
$xml_request='<?xml version="1.0"?><request><data></data></request>';
$url='http://www.myserver.com/xml_request.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_request);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
$result = curl_exec($ch);
curl_close($ch);
我正在试图弄清楚如何在服务器端解析该请求。如果我这样做:
print_r($_POST);
它返回:
Array
(
[<?xml_version] => \"1.0\"?><request><data></data></request>
)
我希望能够将帖子传递给其中一个XML解析器。例如simplexml_load_string()
。我需要访问干净的XML文件。如何访问POST请求,以便获得干净的文件?
答案 0 :(得分:2)
问题在于发布请求的脚本。在将XML字符串发送到服务器之前,需要对其进行编码,以防止服务器解析它。在将XML发布到服务器之前,请尝试通过rawurlencode
运行XML。
再看一下,我看到了另一个问题。看起来CURLOPT_POSTFIELDS
选项希望您自己形成字符串。 Quoth the manual page(粗体是我的):
要在HTTP“POST”操作中发布的完整数据。要发布文件,请在文件前加上@并使用完整路径。 这可以作为urlencoded字符串传递,如'para1 = val1&amp; para2 = val2&amp; ...',或者作为一个数组,字段名称为键,字段数据为值。如果值为数组,Content-Type标题将设置为multipart / form-data。
所以在你的情况下,它会像
curl_setopt($ch, CURLOPT_POSTFIELDS, 'xmlstring='.rawurlencode($xml_request))
然后在接收脚本中,您希望能够以$ _POST ['xmlstring']的形式访问它。
答案 1 :(得分:0)
php://input
允许您在PHP中读取原始POST数据。 例如:
在客户端:
<?php
$ch = curl_init();
$file = file_get_contents("stuff.xml");
$url = "http://traalala.com/foobar";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$file);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>
在服务器端的Controller中:
$post = file_get_contents("php://input");
print $post;
关闭帖子,控制器会抓取帖子数据。
根据stuff.xml