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
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ example.xmlwriter-simple.php
PHP: Creating a simple XML document - Manual
Example #1 Creating a simple XML document ยท <?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);
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

๐ŸŒ
Way2tutorial
way2tutorial.com โ€บ xml โ€บ php-generate-xml.php
PHP Generate XML file - SimpleXML, DOM, Reader/Writer Method
<?php $simple_xml = new SimpleXMLElement('<student></student>'); $simple_xml->addChild('result'); $simple_xml->result[0]->addAttribute('id', 1); $simple_xml->result[0]->addChild('name', 'Opal Kole'); $simple_xml->result[0]->addChild('sgpa', '8.1'); $simple_xml->result[0]->addChild('cgpa', '8.4'); $simple_xml->asXML('simple_xml_create.xml'); ?>
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ creating xml files in php
Creating XML Files in PHP - Scaler Topics
June 10, 2024 - Ensure it's enabled in your PHP configuration (extension=simplexml). ... Use SimpleXMLElement to create the XML structure.
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ php โ€บ php xml tutorial: create, parse, read with example
PHP XML Tutorial: Create, Parse, Read with Example
June 28, 2024 - โ€œecho โ€˜<a href= โ€œโ€˜.$xml_file_name.'โ€>โ€™ . $xml_file_name . โ€˜</a> has been successfully createdโ€™;โ€ creates the link to the XML file. Assuming you saved the file create_movies_list in phptuts/xml folder, browse to the URL http://localhost/phptuts/xml/create_movies_list.php
๐ŸŒ
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 - DOMDocument represents an entire HTML or XML document, serves as the root of the document tree. ... Now, we will create elements of the XML document. It will create new element node using createElement() function. It creates a new instance of ...
๐ŸŒ
Learning About Electronics
learningaboutelectronics.com โ€บ Articles โ€บ How-to-create-an-XML-document-with-PHP.php
How to Create an XML Document with PHP
We add in the file_put_contents() function into the code and into this function we create a separate XML file called books.xml. This is all shown below. So you can see now we have most of the code we previously had, but instead of echoing the contents of the XML tags we wrote onto the current ...
๐ŸŒ
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 - In this tutorial I will be demonstrating how to generate XML or create an XML file using PHP and the SimpleXML extension.
Find elsewhere
๐ŸŒ
Regur
regur.net โ€บ blog โ€บ creation-xml-file-php-simplexml
Creation of XML File in PHP with SimpleXML - Regur Technology Solutions
October 6, 2016 - </plot> <great-lines> <line>PHP solves all my web problems</line> </great-lines> <rating type="thumbs">7</rating> <rating type="stars">5</rating> </movie> </movies> XML; //SimpleXML Object created $movies = new SimpleXMLElement($xmlstr);
๐ŸŒ
GitHub
github.com โ€บ AaronDDM โ€บ XMLBuilder
GitHub - AaronDDM/XMLBuilder: A simple PHP XML builder library written for PHP 7.2+ ยท GitHub
<?php require_once 'vendor/autoload.php'; use AaronDDM\XMLBuilder\XMLBuilder; use AaronDDM\XMLBuilder\Writer\XMLWriterService; use AaronDDM\XMLBuilder\Exception\XMLArrayException; $xmlWriterService = new XMLWriterService(); $xmlBuilder = new XMLBuilder($xmlWriterService); try { $xmlBuilder ->createXMLArray() ->start('Root') ->addCData('1 First Child First Element', 'This is a test') ->add('First Child Second Element', false) ->start('Second Parent') ->add('Second child 1', null, ['myAttr' => 'Attr Value']) ->add('Second child 2', false) ->start('Third Parent') ->add('Child') ->end() ->end() ->add('First Child Third Element') ->end(); var_dump($xmlBuilder->getXML()); } catch (XMLArrayException $e) { var_dump('An exception occurred: ' .
Starred by 28 users
Forked by 4 users
Languages ย  PHP
๐ŸŒ
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.
๐ŸŒ
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 - $xmlString = '<?xml version="1.0" ... <priority>1.00</priority> </url> </urlset>'; $dom = new DOMDocument; $dom->preserveWhiteSpace = FALSE; $dom->loadXML($xmlString); //Save XML as a file $dom->save('xml/sitemap.xml'); Use ...
๐ŸŒ
Code in the Hole
codeinthehole.com โ€บ tips โ€บ creating-large-xml-files-with-php
Creating large XML files with PHP โ€” David Winterbottom
<?php $xmlWriter = new XMLWriter(); $xmlWriter->openMemory(); $xmlWriter->startDocument('1.0', 'UTF-8'); for ($i=0; $i<=10000000; ++$i) { $xmlWriter->startElement('message'); $xmlWriter->writeElement('content', 'Example content'); $xmlWriter->endElement(); // Flush XML in memory to file every ...
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ php_xml_simplexml_read.asp
PHP SimpleXML Parser
This parser provides an easy way to access elements, attributes and textual content of an XML document. Tip: The SimpleXML Parser is a part of the PHP core.