php 将多维数组转换为 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17428323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:52:20  来源:igfitidea点击:

Convert multidimensional array into XML

phpxmlobject

提问by swg1cor14

Please read the bolded line below before you comment that this may be a duplicate. This has nothing to do with SimpleXML.

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

Let me start off by showing how the XML should be laid out. Please ignore the namespaces:

让我首先展示 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>

Notice under hot1:RoomsInformation there is RoomInfo. I'm supposed to be able to send multiple RoomInfo nodes. But I'm using a PHP class to convert an array to this object to be submitted via SOAP.

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

Here's my array before it gets converted to an object:

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

$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) ;

The problem is that after converting to an Object, there is only 1 RoomInfo and its the last one. My thought is because the RoomsInformation array has 2 identical KEY names. So how can I make this work?

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

For your information, here is the SOAP class I use and the arrayToObject function:

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

http://pastebin.com/SBUN0FAF

http://pastebin.com/SBUN0FAF

回答by chrislondon

The problem is, your array is invalid as you suspected because of the duplicate keys. One way to solve the issue is to wrap each "RoomInfo" in its own array like so:

问题是,由于重复键,您的数组无效,正如您怀疑的那样。解决此问题的一种方法是将每个“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"
);

And you can generate the XML like this:

您可以像这样生成 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");
        }
    }
}

I attribute the array_to_xml function to the wonderful author here: https://stackoverflow.com/a/5965940/2200766

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

回答by Tim

It looks as though you should have your array like this, instead;

看起来你应该拥有这样的数组;

$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"
    );

This will preserve the two RoomInfo array elements.

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

回答by Legend Blogs

convert PHP multidimensional or associative array to XML file, and the example code shows how to parse the XML file and convert XML data to array in PHP. I have a two-dimensional input array containing the array of key/element pairs. For better understanding, all the Array to XML conversion code will be grouped together in a PHP function. The generateXML() function converts PHP multidimensional array to XML file format. The data array needs to be passed as a parameter in generateXML() function. This function create an XML document using DOMDocument class and insert the PHP array content in this XML document. At the end, the XML document is saved as an XML file in the specified file location with given file name.

将 PHP 多维或关联数组转换为 XML 文件,示例代码展示了如何在 PHP 中解析 XML 文件并将 XML 数据转换为数组。我有一个包含键/元素对数组的二维输入数组。为了更好地理解,所有数组到 XML 的转换代码都将组合在一个 PHP 函数中。generateXML() 函数将 PHP 多维数组转换为 XML 文件格式。数据数组需要在 generateXML() 函数中作为参数传递。该函数使用 DOMDocument 类创建一个 XML 文档,并在此 XML 文档中插入 PHP 数组内容。最后,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;
}

You only need to use generateXML() function and pass data array in it to convert array to XML in PHP. You can see full detail here and also convert XML to Array

你只需要使用 generateXML() 函数并在其中传递数据数组即可在 PHP 中将数组转换为 XML。您可以在此处查看完整详细信息并将 XML 转换为数组

generateXML($array);