php修改xml檔案內容的方法:先遍歷xml文件;然後透過語句「foreach ($books as $book) {...}」修改內容;最後重新sava一下即可。
本文操作環境:Windows7系統、PHP7.1版,DELL G3電腦
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>
推薦學習:《 PHP影片教學》
以上是php怎麼修改xml文件內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!