将数组保存为xml

时间:2010-09-20 22:23:52

标签: php xml arrays

array(
name => text,
surname => text,
country => text,
date => text
)

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

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

3 个答案:

答案 0 :(得分:7)

// 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;
 }

答案 1 :(得分:5)

使用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 :(得分:2)

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

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

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