Create new XML file and write data to it?

后端 未结 3 445
长情又很酷
长情又很酷 2020-11-30 00:22

I need to create a new XML file and write that to my server. So, I am looking for the best way to create a new XML file, write some base nodes to it, save it. Then open it a

3条回答
  •  孤街浪徒
    2020-11-30 01:02

    DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

    $xml = new DOMDocument();
    $xml_album = $xml->createElement("Album");
    $xml_track = $xml->createElement("Track");
    $xml_album->appendChild( $xml_track );
    $xml->appendChild( $xml_album );
    
    $xml->save("/tmp/test.xml");
    

    To re-open and write:

    $xml = new DOMDocument();
    $xml->load('/tmp/test.xml');
    $nodes = $xml->getElementsByTagName('Album') ;
    if ($nodes->length > 0) {
       //insert some stuff using appendChild()
    }
    
    //re-save
    $xml->save("/tmp/test.xml");
    

提交回复
热议问题