A simple example of adding data to an xml file in php, and adding an xml file in php
Xml file: stu. xml:
<? Xml version = "1.0" encoding = "UTF-8"?> <AllData> <xueshengmen> <xuesheng> <name> Zhang San </name> <yuwen> 80 </yuwen> <shuxue> 90 </shuxue> <yingyu> 70 </yingyu> </xuesheng> <name> Li Si </name> <yuwen> 60 </yuwen> <shuxue> 90 </shuxue> <yingyu> 75 </yingyu> </xuesheng> </xueshengmen> </AllData>
The above file stu. xml provides some student data.
Now you need to add a zongfen attribute to each xuesheng node and its value is equal to the value of yuwen + shuxue + yingyu.
As follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <AllData> <xueshengmen> <xuesheng> <name> Zhang San </name> <yuwen> 80 </yuwen> <shuxue> 90 </shuxue> <yingyu> 70 </yingyu> <zongfen> 240 </zongfen> </xuesheng> <name> Li Si </name> <yuwen> 60 </yuwen> <shuxue> 90 </shuxue> <yingyu> 75 </yingyu> <zongfen> 2225 </zongfen> </xuesheng> </xueshengmen> </AllData>
Php is used for implementation:
<? Php $ doc = new DOMDocument (); $ doc-> load ('stu. xml '); $ students = $ doc-> getElementsByTagName ("xuesheng"); foreach ($ students as $ stu) {$ yuwen = $ stu-> getElementsByTagName ("yuwen ") -> item (0)-> nodeValue; $ shuxue = $ stu-> getElementsByTagName ("shuxue")-> item (0)-> nodeValue; $ yingyu = $ stu-> getElementsByTagName ("yingyu")-> item (0)-> nodeValue; $ zongfen = $ stu-> getElementsByTagName ("zongfen ") -> item (0 )-> NodeValue; if ($ zongfen) {echo "the node already exists and will not be added !"; Continue;} $ zongfen = $ yuwen + $ shuxue + $ yingyu; $ newNode = $ doc-> createElement ("zongfen", $ zongfen ); $ stu-> appendChild ($ newNode);} $ result = $ doc-> saveXML ('stu. xml');?>
The simple example of adding data to an xml file in php above is all the content shared by the editor. I hope to give you a reference and support for the help house.