我正在尝试在PHP中测试cURL选项。但是我无法在浏览器上打印XML输出。我收到解析错误。由于某种原因,XML 的开头被截断,因此语法错误。我的客户端代码如下:
<?php
header('Content-type: text/xml');
/**
* Define POST URL and also payload
*/
$xml_data = "<?xml version='1.0'?><member><name>XYZ</name><address>1111 yonge street Toronto Canada</address><businessunit>Hotel </businessunit></member>";
define('XML_PAYLOAD',$xml_data);
define('XML_POST_URL', 'http://localhost:8888/PlatformX/build_xml.php');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
/**
* Execute the request and also time the transaction
*/
$start = array_sum(explode(' ', microtime()));
$retValue = curl_exec($ch);
$stop = array_sum(explode(' ', microtime()));
$totalTime = $stop - $start;
/**
* Check for errors
*/
if ( curl_errno($ch) ) {
$result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
} else {
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
switch($returnCode){
case 404:
$result = 'ERROR -> 404 Not Found';
break;
default:
$result = 'Success';
break;
}
}
/**
* Close the handle
*/
curl_close($ch);
/**
* Output the results and time
*/
echo 'Total time for request: ' . $totalTime . "'n";
echo $result;
print_r($retValue);
/**
* Exit the script
*/
exit(0);
?>
我的服务器侧代码是:
<?php
header('Content-type: text/xml');
foreach( $_POST as $xmlstr ) {
echo $xmlstr;
}
?>
但是我无法在浏览器上打印XML。
请求您的帮助。我得到以下回应
'1.0'?>XYZ
1111 yonge street Toronto Canada
Hotel
我没有获得标签名称,如果我使用header('Content-type: text/xml');
则会出现解析错误。
你告诉 PHP 尝试将 XML 字符串解析为变量。而是你想使用整个输入。因此,请将服务器端代码更改为以下内容:
<?php
header('Content-type: text/xml');
echo file_get_contents("php://input");
确保您的 XML 有效。(例如,将其放入文件)它应该以 <?xml version="1.0"?>
开头 (可选)它可以包含<?xml version="1.0" encoding="UTF-8"?>
编码,强烈建议这样做(解析错误意味着 XML 无效,或者无法确定编码)
另外,请尝试改用header('Content-type: application/xml');
。