数组保存为XML [英] Save array as xml

查看:406
本文介绍了数组保存为XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 阵列(
名称= GT;文本,
姓=>文本,
国家= GT;文本,
日期= GT;文本

1)我怎样才能拯救这个数组文件作为xml文件?

2)如何阅读本文件,然后作为数组?


解决方案

  //保存
$ DOC =新的DOMDocument('1.0');
$ doc-> formatOutput = TRUE;
$根= $ doc->的createElement('根');
$根= $ doc->的appendChild($根);
的foreach($改编为$关键=> $值)
{
   $ EM = $ doc->的createElement($键);
   $文字= $ doc->一个createTextNode($值);
   $的EM>的appendChild($文字);
   $根 - >的appendChild($ EM);}
$ doc->保存('file.xml');
//负荷
 $ ARR =阵列();
 $ DOC =新的DOMDocument();
 $ doc->负载('file.xml');
 $根= $ doc->的getElementsByTagName('根') - GT;项目[0];
 的foreach($根 - >子节点为$项)
 {
   $改编[$本期特价货品>节点名称] = $本期特价货品>的nodeValue;
 }

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

1) How can I save this array to file as xml file?

2) How to read this file then as array?

解决方案

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

这篇关于数组保存为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆