创建新的XML文件并写入数据? [英] Create new XML file and write data to it?

查看:157
本文介绍了创建新的XML文件并写入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个新的XML文件并将其写入我的服务器。所以,我正在寻找最好的方式来创建一个新的XML文件,写一些基本的节点,保存。然后再打开它并写入更多数据。

I need to create a new XML file and write that to my server. So, I am looking for the best way to create a new XML file, write some base nodes to it, save it. Then open it again and write more data.

我一直在使用 file_put_contents()来保存文件。但是,要创建一个新的基础节点,我不知道最好的方法。

I have been using file_put_contents() to save the file. But, to create a new one and write some base nodes I am not sure of the best method.

想法?

推荐答案

DOMDocument 是一个不错的选择。它是专门用于创建和操作XML文档的模块。您可以从头开始创建一个文档,或打开现有文档(或字符串),并导航并修改其结构。

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

重新打开和写入:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

这篇关于创建新的XML文件并写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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