How to generate XML file dynamically using PHP?

I have to generate a xml file dynamically at runtime. Please help me in generating the below XML file dynamically using PHP.

<?xml version="1.0" encoding="UTF-8"?>
     <title>Track 1 - Track Title</title>
     <title>Track 2 - Track Title</title>
     <title>Track 3 - Track Title</title>
     <title>Track 4 - Track Title</title>
     <title>Track 5 - Track Title</title>
     <title>Track 6 - Track Title</title>
     <title>Track 7 - Track Title</title>
     <title>Track 8 - Track Title</title>

11 thoughts on “How to generate XML file dynamically using PHP?

  1. user
    $query=mysql_query("select * from tablename")or die(mysql_error()); 
        $xml .="<mail_address>\n\t\t";
        $xml .= "<id>".$data['id']."</id>\n\t\t";
        $xml .= "<email>".$data['email_address']."</email>\n\t\t";
        $xml .= "<verify_code>".$data['verify']."</verify_code>\n\t\t";
        $xml .= "<status>".$data['status']."</status>\n\t\t";
    $xmlobj=new SimpleXMLElement($xml);

    Its simple just connect with your database it will create test.xml file in your project folder

  2. user

    An easily broken way to do this is :

    // Send the headers
    header('Content-type: text/xml');
    header('Pragma: public');
    header('Cache-control: private');
    header('Expires: -1');
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    echo '<xml>';
    // echo some dynamically generated content here
        <title>track_number - track_title</title>
    echo '</xml>';

    save it as .php

  3. user

    Take a look at the Tiny But Strong templating system. It’s generally used for templating HTML but there’s an extension that works with XML files. I use this extensively for creating reports where I can have one code file and two template files – htm and xml – and the user can then choose whether to send a report to screen or spreadsheet.

    Another advantage is you don’t have to code the xml from scratch, in some cases I’ve been wanting to export very large complex spreadsheets, and instead of having to code all the export all that is required is to save an existing spreadsheet in xml and substitute in code tags where data output is required. It’s a quick and a very efficient way to work.

  4. user

    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

    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.

        /* 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 cicle */
        $currentTrack = $domtree->createElement("track");
        $currentTrack = $xmlRoot->appendChild($currentTrack);
        $currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));
        $currentTrack = $domtree->createElement("track");
        $currentTrack = $xmlRoot->appendChild($currentTrack);
        $currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));
        /* get the xml printed */
        echo $domtree->saveXML();

    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

  5. user

    I’d use SimpleXMLElement.

    $xml = new SimpleXMLElement('<xml/>');
    for ($i = 1; $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');

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

  6. user

    Hope this code may help you out. Easy and simple solution

    $dom = new DOMDocument();
    $dom->encoding = 'utf-8';
    $dom->xmlVersion = '1.0';
    $dom->formatOutput = true;
    $xml_file_name = './movies_list.xml'; //You can give your path to save file.
    $root = $dom->createElement('Movies');
        $movie_node = $dom->createElement('movie');
        $attr_movie_id = new DOMAttr('movie_id', '5467');
            $child_node_title = $dom->createElement('Title', 'The Campaign');
            $child_node_year = $dom->createElement('Year', 2012);
            $child_node_genre = $dom->createElement('Genre', 'The Campaign');
            $child_node_ratings = $dom->createElement('Ratings', 6.2);

    For more information visit this to get information in details:

  7. user

    I see examples with both DOM and SimpleXML, but none with the XMLWriter.

    Please keep in mind that from the tests I’ve done, both DOM and SimpleXML are almost twice slower then the XMLWriter and for larger files you should consider using the later one.

    Here’s a full working example, clear and simple that meets the requirements, written with XMLWriter (I’m sure it will help other users):

    // array with the key / value pairs of the information to be added (can be an array with the data fetched from db as well)
    $songs = [
        'song1.mp3' => 'Track 1 - Track Title',
        'song2.mp3' => 'Track 2 - Track Title',
        'song3.mp3' => 'Track 3 - Track Title',
        'song4.mp3' => 'Track 4 - Track Title',
        'song5.mp3' => 'Track 5 - Track Title',
        'song6.mp3' => 'Track 6 - Track Title',
        'song7.mp3' => 'Track 7 - Track Title',
        'song8.mp3' => 'Track 8 - Track Title',
    $xml = new XMLWriter();
    $xml->setIndentString('    ');
    $xml->startDocument('1.0', 'UTF-8');
                foreach($songs as $song => $track){
                        $xml->writeElement('path', $song);
                        $xml->writeElement('title', $track);

Leave a Reply

Your email address will not be published.