无法使用cURL PHP输出xml

时间:2014-04-02 12:20:28

标签: php curl

我正在尝试在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');,我会得到解析错误。

2 个答案:

答案 0 :(得分:1)

您告诉PHP尝试将XML字符串解析为变量。而是你想要使用整个输入。因此,将服务器端代码更改为:

<?php
header('Content-type: text/xml');

echo file_get_contents("php://input");

答案 1 :(得分:0)

确保您的XML有效。 (例如,将它放到一个文件中)它应该以{{1​​}}开头。可选地,它可以包括<?xml version="1.0"?>编码,强烈建议这样做(解析错误意味着XML无效,或者编码无法确定)

另外,请尝试使用<?xml version="1.0" encoding="UTF-8"?>