【问题标题】:Save array as xml将数组另存为 xml
【发布时间】:2023-03-31 03:30:01
【问题描述】:
array(
name => text,
surname => text,
country => text,
date => text
)

1) 如何将此数组保存为 xml 文件?

2) 如何将该文件读取为数组?

【问题讨论】:

  • 您是否考虑过使用 JSON 来序列化它?我对 XML 有偏见。脂肪太多=/

标签: php xml arrays


【解决方案1】:

使用 SimpleXML

对于#1(如How to convert array to SimpleXML

<?php
  $xml = new SimpleXMLElement('<root/>');
  array_walk_recursive($test_array, array ($xml, 'addChild'));
  print $xml->asXML("file.xml");

#2

$xml_data_as_object = simplexml_load_file("file.xml")

返回 xml 数据的对象表示。

将对象转换为数组:

$xml_data_as_array = array();
foreach ($xml_data->root as $children) {
   $xml_data_as_array[] = array(
     "name" => $children->name,
     "surname" => $children->surname,
     "country" => $children->country,
     "date" => $children->date
  );
}

【讨论】:

    【解决方案2】:

    看看 Pear 模块 XML::Serializer -- 它还包括 XML::Unserializer。

    http://pear.php.net/package/XML_Serializer/

    http://articles.sitepoint.com/article/xml-php-pear-xml_serializer

    【讨论】:

      【解决方案3】:
      // save
      $doc = new DOMDocument('1.0');
      $doc->formatOutput = true;
      $root = $doc->createElement('root');
      $root = $doc->appendChild($root);
      foreach($arr as $key=>$value)
      {
         $em = $doc->createElement($key);       
         $text = $doc->createTextNode($value);
         $em->appendChild($text);
         $root->appendChild($em);
      
      }
      $doc->save('file.xml');
      // load
       $arr = array();
       $doc = new DOMDocument();
       $doc->load('file.xml');
       $root = $doc->getElementsByTagName('root')->items[0];
       foreach($root->childNodes as $item) 
       { 
         $arr[$item->nodeName] = $item->nodeValue;
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2014-09-23
        • 1970-01-01
        • 2012-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多