In XML entry 7: using DOM objects to create XML documents, we have learned how to use the dom class of PHP to create an XML document. However, the function of the dom class is far more than that. today we will learn how to use it to add elements to existing XML documents. in "XML entry 7: using DOM objects to create XML documents, we have learned how to use the PHP dom class to create an XML document. However, the function of the dom class is far more than that. today we will learn how to use it to add elements to existing XML documents.
Let's sort out the business logic for completing the above requirements:
1. load XML documents
2. obtain the parent element to which you want to add child elements
3. create the elements you want to add
4. add child elements to the parent element obtained before.
Before that, we have learned the dom class methods required in Part 1, 3, and 4. now let's introduce how to obtain an element in an XML document. Here we need to use two dom class methods: getElementsByTagName (name) and item (index). We will introduce them one by one.
1. getElementsByTagName (name)
It returns all elements that match the name.
2. item (index)
Element of the specific index in the object set returned by getElementsByTagName (name)
Here is a specific example:
Original XML document: Jiang Shen 23 Male 5.9 9: 00
Next we want Add the previous Element
The PHP code is as follows:
Load ("./2.xml"); // output the original XMLecho $ doc-> saveXML (); echo' '; // How to match all elements with people $ element = $ doc-> getElementsByTagName ("people "); // element whose index is 0 $ first_people = $ element-> item (0); $ money = $ doc-> createElement ("money", "20000 "); $ first_people-> appendChild ($ money); echo $ doc-> saveXML ();?>
Here is a specific example:
Original XML document:
Jiang Shen 23 male 5.9 Jiang Shen 23 male 5.9 20000