I'd use SimpleXMLElement.

<?php

$xml = new SimpleXMLElement('<xml/>');

for (i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

?>

$xml->asXML() can also take a filename as a parameter to save to that file

Answer from Ivan Krechetov on Stack Overflow
Top answer
1 of 8
390

I'd use SimpleXMLElement.

<?php

$xml = new SimpleXMLElement('<xml/>');

for (i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

?>

$xml->asXML() can also take a filename as a parameter to save to that file

2 of 8
191

To create an XMLdocument in PHP you should instance a DOMDocument class, create child nodes and append these nodes in the correct branch of the document tree.

For reference you can read https://www.php.net/manual/en/book.dom.php

Now we will take a quick tour of the code below.

  • at line 2 we create an empty xml document (just specify xml version (1.0) and encoding (utf8))
  • now we need to populate the xml tree:
    • We have to create an xmlnode (line 5)
    • and we have to append this in the correct position. We are creating the root so we append this directly to the domdocument.
    • Note create element append the element to the node and return the node inserted, we save this reference to append the track nodes to the root node (incidentally called xml).

These are the basics, you can create and append a node in just a line (13th, for example), you can do a lot of other things with the dom api. It is up to you.

<?php    
    /* create a dom document with encoding utf8 */
    $domtree = new DOMDocument('1.0', 'UTF-8');

    /* create the root element of the xml tree */
    $xmlRoot = $domtree->createElement("xml");
    /* append it to the document created */
    $xmlRoot = $domtree->appendChild($xmlRoot);



    /* you should enclose the following lines in a loop */
    $currentTrack = $domtree->createElement("track");
    $currentTrack = $xmlRoot->appendChild($currentTrack);
    $currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
    $currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));

    $currentTrack = $domtree->createElement("track");
    $currentTrack = $xmlRoot->appendChild($currentTrack);
    $currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
    $currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));

    /* get the xml printed */
    echo $domtree->saveXML();
?>

Edit: Just one other hint: The main advantage of using an xmldocument (the dom document one or the simplexml one) instead of printing the xml,is that the xmltree is searchable with xpath query

๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ example.xmlwriter-simple.php
PHP: Creating a simple XML document - Manual
<?php $xw = xmlwriter_open_memory(); xmlwriter_set_indent($xw, 1); $res = xmlwriter_set_indent_string($xw, ' '); xmlwriter_start_document($xw, '1.0', 'UTF-8'); // A first element xmlwriter_start_element($xw, 'tag1'); // Attribute 'att1' for element 'tag1' xmlwriter_start_attribute($xw, 'att1'); xmlwriter_text($xw, 'valueofatt1'); xmlwriter_end_attribute($xw); xmlwriter_write_comment($xw, 'this is a comment.'); // Start a child element xmlwriter_start_element($xw, 'tag11'); xmlwriter_text($xw, 'This is a sample text, รค'); xmlwriter_end_element($xw); // tag11 xmlwriter_end_element($xw); // tag1
๐ŸŒ
Way2tutorial
way2tutorial.com โ€บ xml โ€บ php-generate-xml.php
PHP Generate XML file - SimpleXML, DOM, Reader/Writer Method
<?php $dom = new DOMDocument('1.0','UTF-8'); $dom->formatOutput = true; $root = $dom->createElement('student'); $dom->appendChild($root); $result = $dom->createElement('result'); $root->appendChild($result); $result->setAttribute('id', 1); $result->appendChild( $dom->createElement('name', 'Opal Kole') ); $result->appendChild( $dom->createElement('sgpa', '8.1') ); $result->appendChild( $dom->createElement('cgpa', '8.4') ); echo '<xmp>'. $dom->saveXML() .'</xmp>'; $dom->save('result.xml') or die('XML Create Error'); ?> Result Output ยท <?xml version="1.0" encoding="UTF-8"?> <student> <result id=
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Create and Save XML File using PHP - YouTube
Generate XML in PHP - Video Tutorial to create and save XML file. A simple way to create XML sitemap and save XML file into the directory using PHP.Read tuto...
Published ย  July 4, 2016
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ php โ€บ php xml tutorial: create, parse, read with example
PHP XML Tutorial: Create, Parse, Read with Example
June 28, 2024 - โ€œ$dom->save($xml_file_name);โ€ saves the XML file in the root directory of the web server.
๐ŸŒ
CodexWorld
codexworld.com โ€บ home โ€บ how to create and save xml file using php
How to Create and Save XML File using PHP - CodexWorld
July 5, 2016 - Also, using saveXml() and save() method youโ€™ll be able to output XML document to the browser and save XML document as a file. The saveXml() function puts internal XML document into a string.
๐ŸŒ
Regur
regur.net โ€บ blog โ€บ creation-xml-file-php-simplexml
Creation of XML File in PHP with SimpleXML - Regur Technology Solutions
October 6, 2016 - If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise. ... //Saving XML File $movies->asXML(); OR $movies->saveXML(); OR $movies->asXML(โ€œmovie-details.xmlโ€);
Find elsewhere
๐ŸŒ
Online Web Tutor
onlinewebtutorblog.com โ€บ how-to-create-and-save-xml-file-using-php-tutorial
How to Create and Save XML File using PHP Tutorial
April 2, 2022 - How to Create and Save XML File using PHP Tutorial. How to save XML using PHP. SimpleXMLElement. Generate XML file. PHP saveXML() Function. PHP XML Tutorial: Create with Example.
๐ŸŒ
Learning About Electronics
learningaboutelectronics.com โ€บ Articles โ€บ How-to-create-an-XML-document-with-PHP.php
How to Create an XML Document with PHP
This way, it's just as if you created an XML document (with .xml extension) and wrote it complete with XML tags. To do this, the following code above, just needs a slight modification. We add in the file_put_contents() function into the code and into this function we create a separate XML file ...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ creating xml files in php
Creating XML Files in PHP - Scaler Topics
June 10, 2024 - In your PHP configuration file (php.ini), consider enabling short tags (short_open_tag = On) for more concise XML generation. Create a new PHP script (e.g., format_and_save_xml.php) using the opening and closing PHP tags:
๐ŸŒ
Xmlobjective
xmlobjective.com โ€บ create-an-xml-document-using-php
Create An XML Document using PHP | XML Objective
Create and add a few elements, an attribute, and a string. For this, we will need a HTML tag structure. The data will be saved in an .xml file called example_dom.xml on the server. PHP must have the permission to write on the server.
๐ŸŒ
Rip Tutorial
riptutorial.com โ€บ create an xml file using xmlwriter
PHP Tutorial => Create an XML file using XMLWriter
$xml->startElement('foo'); $xml->writeAttribute('bar', 'baz'); $xml->writeCdata('Lorem ipsum'); $xml->endElement(); ... Get monthly updates about new articles, cheatsheets, and tricks.
๐ŸŒ
Design2Code
design2code.co.za โ€บ home โ€บ d2c blog โ€บ how to build xml using php and simplexml
How to build XML using PHP and SimpleXML - Design2Code
May 15, 2020 - //Save the output to a variable $content = $xml->asXML(); //now open a file to write to $handle = fopen('movies.xml', "w"); //Write the contents to the file fwrite($handle, $content); //Close the file fclose($handle); The above should create ...
๐ŸŒ
Alex Web Develop
alexwebdevelop.com โ€บ home โ€บ how to create xml documents from scratch with php
How to create XML documents from scratch with PHP
August 21, 2022 - For example, you could decide to create the document from scratch with XMLWriter (taking advantage of its performance and its functionalities) and edit it later with SimpleXML for changing attributes or adding new nodes. Now letโ€™s see the last extension. DOM is the most powerful PHP extension for creating and editing XML documents.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-generate-an-xml-file-dynamically-using-php
How to generate an XML file dynamically using PHP? - GeeksforGeeks
July 26, 2024 - Till now, we have created an XML file. So to display this we are going to use an echo tag that shows the data from a file in XML format. To save the XML file we will use the save command.
Top answer
1 of 1
28

This is probably what you are looking for.


    //Creates XML string and XML document using the DOM 
    $dom = new DomDocument('1.0', 'UTF-8'); 

    //add root
    $root = $dom->appendChild($dom->createElement('Root'));

    //add NodeA element to Root
    $nodeA = $dom->createElement('NodeA');
    $root->appendChild($nodeA);

    // Appending attr1 and attr2 to the NodeA element
    $attr = $dom->createAttribute('attr1');
    $attr->appendChild($dom->createTextNode('some text'));
    $nodeA->appendChild($attr);
/*
** insert more nodes
*/

    $dom->formatOutput = true; // set the formatOutput attribute of domDocument to true

    // save XML as string or file 
    $test1 = $dom->saveXML(); // put string in test1
    $dom->save('test1.xml'); // save as file

For more information, have a look at the DOM Documentation.

To do what you want:


    //Creates XML string and XML document using the DOM 
    $dom = new DomDocument('1.0', 'UTF-8'); 

    //add root == jukebox
    $jukebox = $dom->appendChild($dom->createElement('jukebox'));

    for ($i = 0; $i < count($arrayWithTracks); $i++) {

        //add track element to jukebox
        $track = $dom->createElement('track');
        $jukebox->appendChild($track);

        // Appending attributes to track
        $attr = $dom->createAttribute('source');
        $attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['source']));
        $track->appendChild($attr);
        $attr = $dom->createAttribute('artist');
        $attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['artist']));
        $track->appendChild($attr);
        $attr = $dom->createAttribute('album');
        $attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['album']));
        $track->appendChild($attr);
        $attr = $dom->createAttribute('title');
        $attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['title']));
        $track->appendChild($attr);
    }

    $dom->formatOutput = true; // set the formatOutput attribute of domDocument to true

    // save XML as string or file 
    $test1 = $dom->saveXML(); // put string in test1
    $dom->save('test1.xml'); // save as file

Cheers