This article mainly introduces the principles and methods of using PHP to modify and delete XML content. The article introduces it in detail through sample code. I believe it will be helpful for everyone's understanding and learning. Friends who are interested You can use it as a reference, let’s take a look below.
This article mainly introduces the method of modifying and deleting XML content with PHP. Without further ado, let’s look at the example
The schematic diagram is as follows
Example code
example.xml
<?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>
First traverse the xml document
<?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>"; }
The running result is:
1-title1 2-title2 3-title3 4-title4 5-title5
Modification:
<?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');
After modification:
<?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>
Delete operation:
<?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');
The result after deletion is:
<?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>
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHP method to implement regular replacement of punctuation marks with spaces
PHP implements the algorithm for calculating lottery probability
php The three-level navigation menu implemented by jQuery
The above is the detailed content of Example of modifying and deleting XML content with PHP. For more information, please follow other related articles on the PHP Chinese website!