php 创建新的 XML 文件并向其中写入数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2038535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create new XML file and write data to it?
提问by Nic Hubbard
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.
我需要创建一个新的 XML 文件并将其写入我的服务器。因此,我正在寻找创建新 XML 文件、向其中写入一些基本节点并保存的最佳方法。然后再次打开它并写入更多数据。
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.
我一直在用file_put_contents()保存文件。但是,要创建一个新节点并编写一些基本节点,我不确定最佳方法。
Ideas?
想法?
回答by zombat
DOMDocumentis 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.
DOMDocument是一个不错的选择。它是一个专门为创建和操作 XML 文档而设计的模块。您可以从头开始创建文档,或打开现有文档(或字符串)并导航和修改其结构。
$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");
To re-open and write:
重新打开并写入:
$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");
回答by Robert Christie
PHP has several libraries for XML Manipulation.
PHP 有几个用于XML 操作的库。
The Document Object Model(DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
该文档对象模型(DOM)方法(这是一个W3C标准,如果你已经在其他环境中使用它,如Web浏览器或Java等应该熟悉)。允许您按如下方式创建文档
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
即使您以前没有接触过 DOM,也值得花一些时间研究它,因为该模型在许多语言/环境中使用。
回答by Daniele Orlando
With FluidXMLyou can generate and store an XML document very easily.
使用FluidXML,您可以非常轻松地生成和存储 XML 文档。
$doc = fluidxml();
$doc->add('Album', true)
->add('Track', 'Track Title');
$doc->save('album.xml');
Loading a document from a file is equally simple.
从文件加载文档同样简单。
$doc = fluidify('album.xml');
$doc->query('//Track')
->attr('id', 123);

