How to modify xml file in php

藏色散人
Release: 2023-03-04 17:06:01
Original
3048 people have browsed it

How to modify the xml file in php: first open the xml file; then traverse the xml document; then reassign the content of the xml file; and finally save the file.

How to modify xml file in php

# Recommended: "

PHP Video Tutorial

PHP Principles and methods of modifying and deleting XML content

How to modify xml file in php

For example:

example.xml

  title1   title2   title3   title4   title5 
Copy after login

First traverse the xml document

load('example.xml'); $books = $doc -> getElementsByTagName("book"); //遍历 foreach ($books as $book) { echo $book->getAttribute('id')."-"; echo $book->getElementsByTagName("title")->item(0)->nodeValue; echo "
"; }
Copy after login

The running result is:

1-title1

2-title2
3-title3
4-title4
5-title5

Modification:

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 "
"; } } //对文件做修改后,一定要记得重新sava一下,才能修改掉原文件 $doc -> save('example.xml');
Copy after login

After modification:

  title1   title2   33333   title4   title5 
Copy after login

Deletion operation:

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');
Copy after login

The result after deletion is:

  title1   title2   33333   title5 
Copy after login

The above is the detailed content of How to modify xml file in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!