Need Assistance With Inserting New Child XML Eleme

2019-09-12 03:21发布

问题:

I've been browsing around for hours now and there is no simple explaination or demonstration of how to insert a new child element into an XML file and then save the XML file.

Here is the XML Tree.. (very simple)

< book > 

    <chapter> 
        <title>Everyday Italian</title> 
        <year>2005</year> 
    </chapter> 
    <chapter> 
        <title>Harry Potter</title> 
        <year>2005</year> 
    </chapter> 
    <chapter> 
        <title>XQuery Kick Start</title> 
        <year>2003</year>   
    </chapter> 

< / book > 

... I would deeply appreciate any help with this. Once again to recap, I have a PHP file and it its goal is to insert a new "chapter" with specifieid "title" and "year" and then save the new file (basically overwriting the book.xml file)

回答1:

There is an example inside the php-manual which gives you all informations you need: http://php.net/manual/en/domdocument.save.php

The methods you need:

  • DOMDocument->load()
    //load xml from a file
  • DOMDocument->createElement()
    //create a element-node
  • DOMDocument->createTextNode()
    //create a textNode
  • DOMNode->appendChild()
    //append one node to another
  • DOMDocument->save()
    //save XML into a file

,

<?php
  //create a document
  $doc=new DOMDocument;
  //load the file
  $doc->load('book.xml');
  //create chapter-element
  $chapter=$doc->createElement('chapter');
  //create title-element
  $title=$doc->createElement('title');
  //insert text to the title
  $title->appendChild($doc->createTextNode('new title for a new chapter'));
  //create year-element
  $year=$doc->createElement('year');
  //insert text to the year
  $year->appendChild($doc->createTextNode('new year for a new chapter'));
  //append title and year to the chapter
  $chapter->appendChild($title);  
  $chapter->appendChild($year);  
  //append the chapter to the root-element
  $doc->documentElement->appendChild($chapter);  
  //save it into the file
  $doc->save('book.xml');
?>