Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new XML file and write data to it?

Tags:

file

php

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.

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.

Ideas?

like image 376
Nic Hubbard Avatar asked Jan 10 '10 20:01

Nic Hubbard


People also ask

How do you create an XML file and write it in Java?

Steps to create and write XML to a file. Create a Document doc . Create XML elements, attributes, etc., and append to the Document doc . Create a Transformer to write the Document doc to an OutputStream .

How do I write data into an XML file using Python?

Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.

How do I create and edit an XML file?

Add a new XML file to a projectFrom the Project menu, select Add New Item. Select XML File from the Templates pane. Enter the filename in the Name field and press Add. The XML file is added to the project and opens in the XML editor.


2 Answers

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"); 

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"); 
like image 155
zombat Avatar answered Sep 26 '22 12:09

zombat


PHP has several libraries for XML Manipulation.

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

<?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.

like image 27
Robert Christie Avatar answered Sep 26 '22 12:09

Robert Christie