PHP嵌套带有属性的soap XML


php nested soap xml with attributes

我需要用soap生成这个xml,但是我无法创建一个带有属性的嵌套xml。

I am able to do this

<ns1:SelectedSupplements>
          <ns1:SupplementInfo suppId="16" supTotalPrice="0.00" suppType="4" />
          <ns1:SupplementInfo suppId="1000615" supTotalPrice="360.00" suppType="8" />
</ns1:SelectedSupplements>

但不是这个

<ns1:SelectedSupplements>
          <ns1:SupplementInfo suppId="16" supTotalPrice="0.00" suppType="4" />
          <ns1:SupplementInfo suppId="1000615" supTotalPrice="360.00" suppType="8">
              <ns1:SupAgeGroup>
                     <ns1:SuppAges suppFrom="1" suppTo="7" suppQuantity="1" suppPrice="40.00"/>
                     <ns1:SuppAges suppFrom="8" suppTo="99" suppQuantity="2" suppPrice="80.00"/>
              </ns1:SupAgeGroup>
          </ns1:SupplementInfo>
    </ns1:SelectedSupplements>
这是我的第一个xml 的代码
$room_class = new stdClass();
$supplement = array();
foreach($results["hotels"]["hotel"][0]["options"]["option"][$key]["fees"]["fee"] as $one_supp)
{
    array_push($supplement, array("suppId"=> $one_supp["suppId"] , "supTotalPrice" => $one_supp["amt"] , "suppType" => $one_supp["supptType"]));
}
$room_class->SelectedSupplements = $supplement;

您可以使用DOMDocument http://php.net/manual/en/class.domdocument.php来完成此操作。

$doc = new DOMDocument();
$doc->formatOutput = true;
$root = $doc->createElement( 'ns1:SelectedSupplements' );
$root = $doc->appendChild( $root );
$supplementInfo = $doc->createElement('ns1:SupplementInfo');
$supplementInfo->setAttribute('suppId', 16);
$supplementInfo->setAttribute('supTotalPrice', 0.00);
$supplementInfo->setAttribute('suppType', 4);
$supAgeGroup = $doc->createElement( 'ns1:SupAgeGroup' );
$supAges = $doc->createElement( 'ns1:SuppAges' );
$supAges->setAttribute( 'suppFrom', 1 );
$supAges->setAttribute( 'suppTo', 7 );
$supAges->setAttribute( 'suppQuantity', 1 );
$supAges->setAttribute( 'suppPrice', 40.00 );
$supAgeGroup->appendChild( $supAges );
$supplementInfo->appendChild( $supAgeGroup );

$root->appendChild( $supplementInfo );
$soapXml= $doc->saveXML( $root );
echo "<pre>";
print_r( htmlspecialchars( $soapXml) );
echo "</pre>" ;