Example of adding data to an xml file in php and adding an xml file in php
Add data to the xml file in php
-
Time: 06:30:37 Source: Network
Introduction: adding data to an xml file using php
Xml file: stu. xml:
Copy the Code 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>
</Xuesheng>
<Xuesheng>
<Name> Li Si </name>
<Yuwen> 60 </yuwen>
<Shuxue> 90 </shuxue>
<Yingyu> 75 </yingyu>
</Xuesheng>
</Xueshengmen>
</AllData> the above stu. xml file 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:
Copy the Code 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>
<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:
Copy the Code as follows: <? 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 ');
?> Related Articles
- DOMDocument for XML operations in PHP
- Php generates simple xml files
- PHP generation of xml file instance code learning