使用SimpleXMLElement创建XML

时间:2018-05-18 09:07:17

标签: php xml simplexml

<?php
$xml =new SimpleXMLElement('<OTA_HotelAvailRQ></OTA_HotelAvailRQ>');

$xml->addChild("AvailRequestSegments");
    $AvailRequestSegment = $xml->addChild("AvailRequestSegment");
        $StayDateRange = $AvailRequestSegment->addChild("StayDateRange");
                $StayDateRange->addAttribute("Duration", "P2N");
                $StayDateRange->addAttribute("Start", $Start);
                $StayDateRange->addAttribute("End", $End);
        $RoomStayCandidates = $AvailRequestSegment->addChild("RoomStayCandidates");
                $RoomStayCandidates->addAttribute("123", "321");

        $HotelSearchCriteria = $AvailRequestSegment->addChild("HotelSearchCriteria");

echo $xml->asXML();
?>

我需要生成的XML是

<OTA_HotelAvailRQ>
   <AvailRequestSegments>
      <AvailRequestSegment>
         <StayDateRange Duration="P2N" Start="2018-10-17+03:00" End="2018-10-19+03:00" />
         <RoomStayCandidates>
            <RoomStayCandidate Quantity="1">
               <GuestCounts IsPerRoom="true">
                  <GuestCount Count="2" AgeQualifyingCode="10" />
               </GuestCounts>
            </RoomStayCandidate>
         </RoomStayCandidates>
         <HotelSearchCriteria>
            <Criterion ExactMatch="false">
               <Position />
               <Address FormattedInd="true">
                  <CityName>Athens Center</CityName>
                  <County>'.$Country.'</County>
                  <CountryName Code="GR" />
               </Address>
            </Criterion>
         </HotelSearchCriteria>
      </AvailRequestSegment>
   </AvailRequestSegments>
</OTA_HotelAvailRQ>

但每当我将一个子[RoomStayCandidates]节点添加到$AvailRequestSegment时,它就会作为子节点添加到$StayDateRange

为我的代码生成的XML是 XML Generated for My code

我认为我的代码是正确的。但我没有得到确切的输出。 请帮助解决这个问题。 TIA

1 个答案:

答案 0 :(得分:0)

<?php
$xml =new SimpleXMLElement('<OTA_HotelAvailRQ></OTA_HotelAvailRQ>');

$xml->addChild("AvailRequestSegments");
    $AvailRequestSegment = $xml->addChild("AvailRequestSegment");
        $StayDateRange = $AvailRequestSegment->addChild("StayDateRange");
                $StayDateRange->addAttribute("Duration", "P2N");
                $StayDateRange->addAttribute("Start", $Start);
                $StayDateRange->addAttribute("End", $End);
        $RoomStayCandidates = $AvailRequestSegment->addChild("RoomStayCandidates");
                $RoomStayCandidates->addAttribute("123", "321");

        $HotelSearchCriteria = $AvailRequestSegment->addChild("HotelSearchCriteria");

echo $xml->asXML();
?>

有效。谢谢。