本文主要介绍的是PHP对XML内容进行修改和删除的方法,下面话不多说,我们来看实例
原理图如下
示例代码
example.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<? xml version = "1.0" encoding = "utf-8" ?> < root > < book id = "1" > < title >title1</ title > </ book > < book id = "2" > < title >title2</ title > </ book > < book id = "3" > < title >title3</ title > </ book > < book id = "4" > < title >title4</ title > </ book > < book id = "5" > < title >title5</ title > </ book > </ root > |
首先遍历一下该xml文档
1
|
<?php $doc = new DOMDocument(); $doc ->load( 'example.xml' ); $books = $doc -> getElementsByTagName( "book" ); //遍历 foreach ($books as $book) { echo $book->getAttribute('id')."-"; echo $book->getElementsByTagName("title")->item(0)->nodeValue; echo "<br>"; } |
运行结果为:
1
2
3
4
5
|
1-title1 2-title2 3-title3 4-title4 5-title5 |
修改:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php $doc = new DOMDocument(); $doc ->load( 'example.xml' ); $books = $doc -> getElementsByTagName( "book" ); //遍历 foreach ( $books as $book ) { //将id=3的title设置为33333 if ( $book ->getAttribute( 'id' )==3){ echo $book ->getAttribute( 'id' ). "-" ; echo $book ->getElementsByTagName( "title" )->item(0)->nodeValue= "33333" ; echo "<br>" ; } } //对文件做修改后,一定要记得重新sava一下,才能修改掉原文件 $doc -> save( 'example.xml' ); |
修改之后为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<? xml version = "1.0" encoding = "utf-8" ?> < root > < book id = "1" > < title >title1</ title > </ book > < book id = "2" > < title >title2</ title > </ book > < book id = "3" > < title >33333</ title > </ book > < book id = "4" > < title >title4</ title > </ book > < book id = "5" > < title >title5</ title > </ book > </ root > |
删除操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php $doc = new DOMDocument(); $doc ->load( 'example.xml' ); $root = $doc -> documentElement; //根标签 $books = $doc -> getElementsByTagName( "book" ); //遍历 foreach ( $books as $book ) { //将id=4的删除 if ( $book ->getAttribute( 'id' )==4){ $root ->removeChild( $book ); } } //对文件做修改后,一定要记得重新sava一下,才能修改掉原文件 $doc -> save( 'example.xml' ); |
删除后的结果为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<? xml version = "1.0" encoding = "utf-8" ?> < root > < book id = "1" > < title >title1</ title > </ book > < book id = "2" > < title >title2</ title > </ book > < book id = "3" > < title >33333</ title > </ book > < book id = "5" > < title >title5</ title > </ book > </ root > |
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。