将多维数组转换为XML

时间:2013-07-02 14:30:21

标签: php xml object

在您评论此内容可能重复之前,请阅读下面的粗体。这与SimpleXML无关。

让我首先展示如何布局XML。请忽略命名空间:

 <hot:SearchHotels>
     <hot:request>
        <hot1:Destination>?</hot1:Destination>
        <hot1:HotelCityName>?</hot1:HotelCityName>
        <hot1:HotelLocationName>?</hot1:HotelLocationName>
        <hot1:HotelName>?</hot1:HotelName>
        <hot1:CheckIn>?</hot1:CheckIn>
        <hot1:CheckOut>?</hot1:CheckOut>
        <hot1:RoomsInformation>
           <!--Zero or more repetitions:-->
           <hot1:RoomInfo>
              <hot1:AdultNum>?</hot1:AdultNum>
              <hot1:ChildNum>?</hot1:ChildNum>
              <!--Optional:-->
              <hot1:ChildAges>
                 <!--Zero or more repetitions:-->
                 <hot1:ChildAge age="?"/>
              </hot1:ChildAges>
           </hot1:RoomInfo>
        </hot1:RoomsInformation>
        <hot1:MaxPrice>?</hot1:MaxPrice>
        <hot1:StarLevel>?</hot1:StarLevel>
        <hot1:AvailableOnly>?</hot1:AvailableOnly>
        <hot1:PropertyType>?</hot1:PropertyType>
        <hot1:ExactDestination>?</hot1:ExactDestination>
     </hot:request>
  </hot:SearchHotels>

在hot1下注意:RoomsInformation有RoomInfo。我应该能够发送多个RoomInfo节点。 但我正在使用PHP类将数组转换为此对象以通过SOAP提交。

这是我的数组在转换为对象之前:

$param = array(
            "Destination" => $destcode,
            "HotelCityName" => $city,
            "HotelLocationName" => "",
            "HotelName" => "",
            "CheckIn" => date("Y-m-d", strtotime($checkin)),
            "CheckOut" => date("Y-m-d", strtotime($checkout)),
            "RoomsInformation" => array (
                "RoomInfo" => array(
                        "AdultNum" => 2,
                        "ChildNum" => 1,
                        "ChildAges" => array(
                            "ChildAge" => array(
                                "age"=>11
                            )
                        )
                    ),
                "RoomInfo" => array(
                        "AdultNum" => 1,
                        "ChildNum" => 0,
                        "ChildAges" => array(
                            "ChildAge" => array(
                                "age"=>0
                            )
                        )
                    )
            ),
            "MaxPrice" => 0,
            "StarLevel" => 0,
            "AvailableOnly" => "false",
            "PropertyType" => "NotSet",
            "ExactDestination" => "false"
        );

$param = arrayToObject($param) ;
$obj = new stdClass(); 
$obj->request=$param;
$result = $test->SearchHotels($obj) ;

问题是在转换为Object之后,只有一个RoomInfo和最后一个。我的想法是因为RoomsInformation数组有两个相同的KEY名称。那么我怎样才能做到这一点呢?

有关您的信息,这里是我使用的SOAP类和arrayToObject函数:

http://pastebin.com/SBUN0FAF

4 个答案:

答案 0 :(得分:9)

问题是,由于密钥重复,您的阵列无效。解决问题的一种方法是将每个“RoomInfo”包装在它自己的数组中,如下所示:

$param = array(
    "Destination" => $destcode,
    "HotelCityName" => $city,
    "HotelLocationName" => "",
    "HotelName" => "",
    "CheckIn" => date("Y-m-d", strtotime($checkin)),
    "CheckOut" => date("Y-m-d", strtotime($checkout)),
    "RoomsInformation" => array (
        array(
            "RoomInfo" => array(
                "AdultNum" => 2,
                "ChildNum" => 1,
                "ChildAges" => array(
                    "ChildAge" => array(
                        "age"=>11
                    )
                )
            ),
        ),
        array(
            "RoomInfo" => array(
                "AdultNum" => 1,
                "ChildNum" => 0,
                "ChildAges" => array(
                    "ChildAge" => array(
                        "age"=>0
                    )
                )
            )
        )
    ),
    "MaxPrice" => 0,
    "StarLevel" => 0,
    "AvailableOnly" => "false",
    "PropertyType" => "NotSet",
    "ExactDestination" => "false"
);

您可以像这样生成XML:

// create simpleXML object
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><SearchHotels></SearchHotels>");
$node = $xml->addChild('request');

// function call to convert array to xml
array_to_xml($param, $node);

// display XML to screen
echo $xml->asXML();
die();

// function to convert an array to XML using SimpleXML
function array_to_xml($array, &$xml) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml->addChild("$key");
                array_to_xml($value, $subnode);
            } else {
                array_to_xml($value, $xml);
            }
        } else {
            $xml->addChild("$key","$value");
        }
    }
}

我将array_to_xml函数归于这里出色的作者:https://stackoverflow.com/a/5965940/2200766

答案 1 :(得分:0)

看起来你应该拥有这样的数组,而不是

$param = array(
        "Destination" => $destcode,
        "HotelCityName" => $city,
        "HotelLocationName" => "",
        "HotelName" => "",
        "CheckIn" => date("Y-m-d", strtotime($checkin)),
        "CheckOut" => date("Y-m-d", strtotime($checkout)),
        "RoomsInformation" => array (
            "RoomInfo" => array(
                  array(
                    "AdultNum" => 2,
                    "ChildNum" => 1,
                    "ChildAges" => array(
                        "ChildAge" => array(
                            "age"=>11
                        )
                    )
                  ),
                  array(
                    "AdultNum" => 1,
                    "ChildNum" => 0,
                    "ChildAges" => array(
                        "ChildAge" => array(
                            "age"=>0
                        )
                    )
                )
            )
        ),
        "MaxPrice" => 0,
        "StarLevel" => 0,
        "AvailableOnly" => "false",
        "PropertyType" => "NotSet",
        "ExactDestination" => "false"
    );

这将保留两个RoomInfo数组元素。

答案 2 :(得分:0)

将PHP多维或关联数组转换为XML文件,示例代码显示了如何在PHP中解析XML文件并将XML数据转换为数组。我有一个二维输入数组,其中包含键/元素对的数组。为了更好地理解,所有从Array到XML的转换代码都将组合在一个PHP函数中。 generateXML()函数将PHP多维数组转换为XML文件格式。数据数组需要作为generateXML()函数中的参数传递。此函数使用DOMDocument类创建XML文档,并将PHP数组内容插入此XML文档。最后,将XML文档以给定文件名的形式另存为XML文件。

function generateXML($data) {
$title = $data['department'];
$rowCount = count($data['employe']);

//create the xml document
$xmlDoc = new DOMDocument();

$root = $xmlDoc->appendChild($xmlDoc->createElement("employe_info"));
$root->appendChild($xmlDoc->createElement("title",$title));
$root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
$tabUsers = $root->appendChild($xmlDoc->createElement('rows'));

foreach($data['employe'] as $user){
    if(!empty($user)){
        $tabUser = $tabUsers->appendChild($xmlDoc->createElement('employe'));
        foreach($user as $key=>$val){
            $tabUser->appendChild($xmlDoc->createElement($key, $val));
        }
    }
}

header("Content-Type: text/plain");

//make the output pretty
$xmlDoc->formatOutput = true;

//save xml file
$file_name = str_replace(' ', '_',$title).'.xml';
$xmlDoc->save($file_name);

//return xml file name
return $file_name;
}

您只需要使用generateXML()函数并在其中传递数据数组即可将数组转换为PHP中的XML。 You can see full detail here and also convert XML to Array

generateXML($array);

答案 3 :(得分:0)

简单地使用这个函数,其中 $data 是多维数组

function array_to_xml( $data ) {
         $xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

         foreach( $data as $key => $value ) {
           $node = $xml_data->addChild('row_' . $key);

           foreach( $value as $keyx => $valuex ) {
             $node->addChild($keyx,$valuex);
            }


          }
          return $xml_data->asXML();
     }