How to generate XML file dynamically using PHP?

前端 未结 7 2261
失恋的感觉
失恋的感觉 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:41

    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->openURI('songs.xml');
    $xml->setIndent(true);
    $xml->setIndentString('    ');
    $xml->startDocument('1.0', 'UTF-8');
        $xml->startElement('xml');
                foreach($songs as $song => $track){
                    $xml->startElement('track');
                        $xml->writeElement('path', $song);
                        $xml->writeElement('title', $track);
                    $xml->endElement();
                }
        $xml->endElement();
    $xml->endDocument();
    $xml->flush();
    unset($xml);
    

提交回复
热议问题