How to generate XML file dynamically using PHP?

前端 未结 7 2266
失恋的感觉
失恋的感觉 2020-11-22 00:32

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



        
7条回答
  •  粉色の甜心
    2020-11-22 00:47

    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 http://it.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.

    createElement("xml");
        /* append it to the document created */
        $xmlRoot = $domtree->appendChild($xmlRoot);
    
        $currentTrack = $domtree->createElement("track");
        $currentTrack = $xmlRoot->appendChild($currentTrack);
    
        /* you should enclose the following two lines in a cicle */
        $currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
        $currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));
    
        $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

提交回复
热议问题