本文主要介紹的是PHP對XML內容進行修改和刪除的方法,下面話不多說,我們來看實例
原理圖如下
示例代碼
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>
首先遍歷一下該xml文檔
<?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-title1 2-title2 3-title3 4-title4 5-title5
修改:
<?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');
修改之後為:
<?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>
刪除操作:
<?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');
刪除後的結果為:
<?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>
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。