使用PHP生成XML

时间:2014-04-12 11:59:44

标签: 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>

任何帮助都会受到赞赏。

谢谢。

2 个答案:

答案 0 :(得分: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 +

答案 1 :(得分:0)

首先,你的xml结构不合理。
应该是这样的:

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

迭代获得的结果,并通过结束,形成所需的xml。