【问题标题】:How can I convert a multidimensional PHP Array To XML?如何将多维 PHP 数组转换为 XML?
【发布时间】:2015-04-04 13:00:21
【问题描述】:

1。我能做什么

我知道如何将 XML 转换为多维 PHP 数组,我是这样做的:

$xml = file_get_contents('data.xml');
$data = json_decode(json_encode((array) simplexml_load_string($xml)),1);

现在$data 是我的 PHP 数组。

2。我应该能做什么

但是如果我改变了那个数组并想把它放回文件中呢?我应该可以做相反的事情吗?但我不知道如何..

3。什么不能解决我的问题

这篇文章很接近,但没有以相同的顺序返回数据:How to convert array to SimpleXML

而且它不应该像这样困难吗?:Convert multidimensional array into XML

【问题讨论】:

    标签: php arrays xml type-conversion


    【解决方案1】:

    我遇到了同样的问题,并且在寻找简单解决方案时遇到了问题。下面的解决方案使用 DOMDocument 来允许漂亮的打印。如果你不想要漂亮的打印设置 $doc->formatOutput = FALSE;

    我虚心提交以下PHP函数:

    function array2xml($data, $name='root', &$doc=null, &$node=null){
        if ($doc==null){
            $doc = new DOMDocument('1.0','UTF-8');
            $doc->formatOutput = TRUE;
            $node = $doc;
        }
    
        if (is_array($data)){
            foreach($data as $var=>$val){
                if (is_numeric($var)){
                    array2xml($val, $name, $doc, $node);
                }else{
                    if (!isset($child)){
                        $child = $doc->createElement($name);
                        $node->appendChild($child);
                    }
    
                    array2xml($val, $var, $doc, $child);
                }
            }
        }else{
            $child = $doc->createElement($name);
            $node->appendChild($child);
            $textNode = $doc->createTextNode($data);
            $child->appendChild($textNode);
        }
    
        if ($doc==$node) return $doc->saveXML();
    }//array2xml
    

    使用以下测试数据并调用:

    $array = [
        'name'   => 'ABC',
        'email'  => 'email@email.com',
        'phones' =>
        [
            'phone' =>
            [
                [
                    'mobile' => '9000199193',
                    'land'   => '9999999',
                ],
                [
                    'mobile' => '9000199193',
                    'land'   => '9999999',
                ],
                [
                    'mobile' => '9000199194',
                    'land'   => '5555555',
                ],
                [
                    'mobile' => '9000199195',
                    'land'   => '8888888',
                ],
            ],
        ],
    ];
    
    //Specify the $array and a name for the root container
    echo array2xml($array, 'contact');
    

    你会得到以下结果:

    <?xml version="1.0" encoding="UTF-8"?>
    <contact>
      <name>ABC</name>
      <email>email@email.com</email>
      <phones>
        <phone>
          <mobile>9000199193</mobile>
          <land>9999999</land>
        </phone>
        <phone>
          <mobile>9000199193</mobile>
          <land>9999999</land>
        </phone>
        <phone>
          <mobile>9000199194</mobile>
          <land>5555555</land>
        </phone>
        <phone>
          <mobile>9000199195</mobile>
          <land>8888888</land>
        </phone>
      </phones>
    </contact>
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      遍历数组,用simplexml的dom操作放入XML。或者,对于一种老式的方式,通过一个循环将 XML 连接成一个类似的字符串。 $xmlstring .= '&lt;tag&gt;' . $arr[x][y] .'&lt;/tag&gt;' 然后使用simplexml_load_string 将结果加载到simplexml 中。

      但最好的办法是如果您打算进行更改并再次保存 XML,请从使用 simplexml 切换到数组。使用 simplexml DOM 遍历 XML 文件,而不是将其转换为数组。然后,您对 DOM 所做的任何更改都可以保存,而无需来回转换。

      【讨论】:

      • 我想转换,因为我所做的更改是使用另一个数组完成的,该数组覆盖了这个数组的值。所以这很容易。而且因为将它从 xml 转换为 php 只需要两行代码,这让我想知道是否也可以用两行代码来完成。
      【解决方案3】:

      我也没有找到令人满意的方法,所以我使用上面答案中的输入编写了这个方法。 它使用 DOMDocument 将数组转换为 xml 并调用自身递归。

       /**
           * Creates an XML from a multidimensional array
           * @param $xml DOMDocument
           * @param $array
           * @param false $base_xml
           */
          private function xmlBuilder(&$xml, $array, $base_xml = false)
          {
              /*
               * If a child branch contains an array the method Recursive is called.
               * In this case the original XML must be preserved, since createElement is no longer available on generated elements,
               * only in the original DOMDocument class
               */
              $base_xml = !empty($base_xml) ? $base_xml : $xml;
              foreach($array AS $key => $value){ //Get through the array and assign the entries to the XML
                  if(is_array($value)){
                      $element = $base_xml->createElement($key); //Create element from the key
                      $this->xmlBuilder($element, $value, $base_xml); //Append the child elements under the element
                  }
                  else{ //The element can be generated from key/value
                      $element = $base_xml->createElement($key, $value);
                  }
                  $xml->appendChild($element); //Add element to XML
              }
          }
      

      您可以使用以下方法调用此方法。

      /**
           * Returns an XML string from a data array
           * @param array $data
           * @return mixed
           */
          private function getXml(array $data)
          {         
              $xml = new DOMDocument(self::XML_API_VERSION, self::XML_API_ENCODING); //generate new XML with version and encoding
      
              $this->xmlBuilder($xml, $data); //Pass through the array and generate the XML from it.
              $string = $xml->saveXML(); //generate a string from the generated XML
      
              return $string; //return the generated string
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        • 2015-11-17
        • 2011-12-09
        • 1970-01-01
        • 2012-06-05
        相关资源
        最近更新 更多