2014-04-12 109 views
0

我有以下PHP代碼,我需要從中生成XML。使用PHP生成XML

$hparams["SiteName"]=""; 
$hparams["AccountCode"]=""; 
$hparams["UserName"]='xxxx'; 
$hparams["Password"]='xxxx'; 
$client_header = new SoapHeader('url','AuthenticationData',$hparams,false); 
$cliente = new SoapClient($wsdl); $cliente->__setSoapHeaders(array($client_header)); 
$opta=array(); 
$opta["Search"]["request"]["Origin"]="MAA"; 
$opta["Search"]["request"]["Destination"]="BOM"; 
$opta["Search"]["request"]["DepartureDate"]="2014-05-20T00:00:00"; 
$opta["Search"]["request"]["ReturnDate"]="2014-05-22T00:00:00"; 
$opta["Search"]["request"]["Type"]="OneWay"; 
$opta["Search"]["request"]["CabinClass"]="All"; 
$opta["Search"]["request"]["PreferredCarrier"]=""; 
$opta["Search"]["request"]["AdultCount"]="1"; 
$opta["Search"]["request"]["ChildCount"]="0"; 
$opta["Search"]["request"]["InfantCount"]="0"; 
$opta["Search"]["request"]["SeniorCount"]="0"; 
$opta["Search"]["request"]["IsDirectFlight"]="true"; 
$opta["Search"]["request"]["PromotionalPlanType"]="Normal"; 
$h=array();  
$h= (array)$cliente->__call('Search',$opta); 

如何在PHP中生成上述變量的XML?

格式應該是

<xml> 
<credential> 
<Sitename>sitename</Sitename> 
<AccountCode>ACC Code</AccountCode> 
</credentials> 

<Data> 
<Origin>MAA</Origin> 
<Destination>BOM</Destination> 
</Data> 
</xml> 

任何幫助將升值。

謝謝。

+0

你能分享wsdl的url嗎? – hindmost

+0

傳遞數組作爲參數不起作用? – hindmost

回答

2
<?php 
ini_set('error_reporting', E_ALL); 
$dom = new DomDocument('1.0'); // making xml 

$credentials = $dom->appendChild($dom->createElement('Credentials')); // adding root element <credentials> 

$sitename  = $credentials->appendChild($dom->createElement('Sitename')); // adding element <sitename> in <credentials> 
$accountcode = $credentials->appendChild($dom->createElement('AccountCode')); // adding element <accountcode> in <credentials> 

$sitename->appendChild($dom->createTextNode('sitename')); // adding text in <sitename> 
$accountcode->appendChild($dom->createTextNode('ACC Code')); // adding text in <accountcode> 

$data   = $dom->appendChild($dom->createElement('Data')); 
$origin   = $data->appendChild($dom->createElement('Origin')); 
$destination = $data->appendChild($dom->createElement('Destination')); 

$origin->appendChild($dom->createTextNode('MAA')); 
$destination->appendChild($dom->createTextNode('BOM')); 

$dom->formatOutput = true; // generating xml 

// generating XML as string or file 
$test1 = $dom->saveXML(); 
$dom->save('test1.xml'); 
?> 

我想你可以寫自己迴路;) 附: PHP 5+

0

首先,你的xml結構不好。
它應該是這樣的:

<xml> 
     <credentials> 
      <Sitename>sitename</Sitename> 
      <AccountCode>ACC Code</AccountCode> 
      <Data> 
       <Origin>MAA</Origin> 
       <Destination>BOM</Destination> 
      </Data> 
     </credentials> 
<credentials> 
    ... 
</credentials> 
    </xml> 

迭代所獲得的結果,並且通過concating,形成所需要的XML。