如何使用PHP保存XML

时间:2010-08-24 00:37:18

标签: php xml

任何人都知道如何使用PHP创建和保存XML?我需要这样的东西:

<jukebox>
  <track source="" artist="" album="" title="" />
  <track source="" artist="" album="" title="" />
  <track source="" artist="" album="" title="" />
  <track source="" artist="" album="" title="" />
</jukebox>

1 个答案:

答案 0 :(得分:20)

这可能就是你要找的东西。


    //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

有关详细信息,请查看DOM Documentation

做你想做的事:


    //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

干杯