这是客户端中的代码:
//Create XML Object
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content',"test data");
$newsIntro->addAttribute('type', 'latest');
// URL of api
$url = 'http://localhost:81/demophp/api2.php';
// init CURL
$ch = curl_init($url);
$headers = array(
'Content-type: application/xml',
'Authorization: 123456',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// exist return value
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// method: POST
curl_setopt($ch, CURLOPT_POST, 1);
// parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, ["xml"=>$newsXML->asXML()]);
$result = curl_exec($ch);
curl_close($ch);
这是api2.php
<?php
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
if($header=="Authorization")
echo "$header: $value";
}
$xmlstr=$_POST["xml"];
$myfile = fopen("log.txt", "w") or die("Unable to open file!");
fwrite($myfile, $xmlstr);
fclose($myfile);
$xml= new SimpleXMLElement($xmlstr);
echo $newsXML['newsPagePrefix'];
exit;
如果我删除header
,它将得到xml
。
但是如果我将标题添加到curl
$headers = array(
'Content-type: application/xml',
'Authorization: 123456',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
发生错误无法得到xml
:
Authorization: 123456
Notice: Undefined index: xml in D:\demophp\api2.php on line 8
Fatal error: Uncaught Exception: String could not be parsed as XML in
为什么添加标头后无法获得POSTFIELDS?
答案 0 :(得分:1)
尝试这个curl脚本。它可能对您有用。
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content',"test data");
$newsIntro->addAttribute('type', 'latest');
// URL of api
$url = 'http://localhost:81/demophp/api2.php';
$input_xml = $newsXML->asXML();
// init CURL
$ch = curl_init($url);
$headers = array(
'Content-type: application/xml',
'Authorization: 123456'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// exist return value
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
// method: POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $input_xml);
// parameters
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
这是api2.php的代码
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
if($header=="Authorization")
echo "$header: $value";
}
$data = file_get_contents("php://input");
$xmlstr=$data;
$myfile = fopen("log.txt", "w") or die("Unable to open file!");
fwrite($myfile, $xmlstr);
fclose($myfile);
$xml= new SimpleXMLElement($xmlstr);
echo $xml['newsPagePrefix'];
exit;