2014-04-02 122 views
0

我想在PHP中測試cURL選項。但是我無法在瀏覽器上打印XML輸出。我得到解析錯誤。出於某種原因,XML的開頭被截斷,因此語法錯誤。 我的客戶端代碼如下:無法使用cURL輸出xml PHP

<?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');我得到解析錯誤。

回答

1

你告訴PHP,試圖解析XML字符串變量。而是你想要使用整個輸入。因此,請將您的服務器端代碼更改爲:

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

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

我改變內容類型爲文本/無格式...現在即時得到「 '1.0' 編碼= 'UTF-8' ?> XYZ

1111央街加拿大多倫多
酒店「出於某種原因,我沒有看到<?XML版本=越來越displayed.It只顯示‘1.0’ – Nanda

+0

開始那你改變你的服務器端代碼' echo file_get_contents(「php:// input」);'而不是'foreach'循環?我相應地改變了我的答案。 – akirk

+0

哇,工作!非常感謝。 – Nanda

0

確保你的XML是有效的。 (以文件爲例)它應該以<?xml version="1.0"?>開頭(可選)它可以包括<?xml version="1.0" encoding="UTF-8"?>編碼,這是強烈推薦的(解析錯誤表示XML無效,或者編碼無法確定)

另外,嘗試改爲使用header('Content-type: application/xml');

+0

XML似乎是有效的,我想他只是想在瀏覽器中顯示它以開始。 – akirk

+0

發送標題並回顯內容意味着我想要在瀏覽器中顯示它。你想在瀏覽器中顯示XML,還是要將其顯示爲文本?如果你想做最後一個,那麼你爲什麼發送XML頭? –

+0

我想在瀏覽器上顯示xml。我通過代碼更改爲包含encoding =「UTF-8」也更改了內容類型頭('Content-type:application/xml');仍然沒有運氣。下面是輸出=> '1.0' 編碼= 'UTF-8'> XYZ

1111 Yonge街道加拿大多倫多
飯店 Nanda