xml文件:stu.xml:
php" id="highlighter_701183">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?xml version= "1.0" encoding= "utf-8" ?> <AllData> <xueshengmen> <xuesheng> <name>张三</name> <yuwen>80</yuwen> <shuxue>90</shuxue> <yingyu>70</yingyu> </xuesheng> <xuesheng> <name>李四</name> <yuwen>60</yuwen> <shuxue>90</shuxue> <yingyu>75</yingyu> </xuesheng> </xueshengmen> </AllData> |
以上文件stu.xml提供了部分学生数据。
现在需要在每个xuesheng的节点里面添加一个zongfen的属性并且它的值等于yuwen+shuxue+yingyu的值
如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?xml version= "1.0" encoding= "utf-8" ?> <AllData> <xueshengmen> <xuesheng> <name>张三</name> <yuwen>80</yuwen> <shuxue>90</shuxue> <yingyu>70</yingyu> <zongfen>240</zongfen> </xuesheng> <xuesheng> <name>李四</name> <yuwen>60</yuwen> <shuxue>90</shuxue> <yingyu>75</yingyu> <zongfen>2225</zongfen> </xuesheng> </xueshengmen> </AllData> |
用php来实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?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 “节点已经存在了,不再添加!”; continue ; } $zongfen = $yuwen + $shuxue + $yingyu ; $newNode = $doc ->createElement(“zongfen”, $zongfen ); $stu ->appendChild( $newNode ); } $result = $doc ->saveXML(‘stu.xml'); ?> |
以上这篇php添加数据到xml文件的简单例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。