2016-03-13 30 views
-1

我在瀏覽器中打開URL/API並從服務器獲取低於xml的響應。如何解析xml響應並使用CURL在php中分配變量

<test xmlns:taxInfoDto="com.message.TaxInformationDto"> 
<response> 
<code>0000</code> 
<description>SUCCESS</description> 
</response> 
<accounts> 
<account currency="BDT" accAlias="6553720"> 
<currentBalance>856.13</currentBalance> 
<availableBalance>856.13</availableBalance> 
</account> 
</accounts> 
<transaction> 
<principalAmount>0</principalAmount> 
<feeAmount>0.00</feeAmount> 
<transactionRef>2570277672</transactionRef> 
<externalRef/> 
<dateTime>09/03/2016</dateTime> 
<userName>01823074838</userName> 
<taxInformation totalAmount="0.00"/> 
<additionalData/> 
</transaction> 
</test> 

現在我要分析此XML響應,並將其分配給一個變量,這樣我可以在anywhere.i正在使用下面的PHP代碼使用這個變量的值。

<?php 
$ch = curl_init(); 

// set URL and other appropriate options 
curl_setopt($ch, CURLOPT_URL, "http://x.x.x.x:/ussd/process?  destination=BANGLA&userName=&secondarySource=01"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
$retValue = curl_exec($ch); 
return $retValue; 
?> 

我得到了低於輸出。

0000SUCCESS856.13 856.13 00.00257027770913/03/201601823074838 

任何人都可以請幫我我如何解析每個值並將其分配給一個變量。

+0

嘗試按Ctrl + U – Deep

+0

我不清楚你的point..can你澄清,請... – bKashOST

+0

您必須添加curlopt的其他選項才能使curl返回響應主體,或者使用輸出緩衝來捕獲輸出。 – GordonM

回答

1

一種可能的解決辦法是添加CURLOPT_RETURNTRANSFER選項:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

從手冊:

TRUE返回傳送作爲 curl_exec的返回值的字符串()代替直接輸出。

可以使用例如simplexml_load_string加載返回的字符串,並訪問其屬性:

<?php 
$ch = curl_init(); 

// set URL and other appropriate options 
curl_setopt($ch, CURLOPT_URL, "http://x.x.x.x:/ussd/process?  destination=BANGLA&userName=&secondarySource=01"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$retValue = curl_exec($ch); 

$simpleXMLElement = simplexml_load_string($retValue); 
$description = (string)$simpleXMLElement->response->description; 
$username = (string)$simpleXMLElement->transaction->userName; 
// etc .. 
+0

非常感謝。它完全適合我... – bKashOST