介绍
这篇文章给大家分享的是有关php修改xml文件的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。
php修改xml文件的方法:首先打开xml文件,然后遍历一下xml文档,接着对xml文件内容进行重新赋值,最后保存文件即可。
引用>
php修改和删除xml内容的原理和方法
例如:
的例子。xml
& lt; ?xml version=?.0”;编码=皍tf-8" ?祝辞& lt; root> & lt;书id=?“比; & lt; title> title1 & lt;/book> & lt;书id=?“比; & lt; title> title2 & lt;/book> & lt;书id=?“在 & lt; title> title3 & lt;/book> & lt;书id=?“比; & lt; title> title4 & lt;/book> & lt;书id=?“比; & lt; title> title5 & lt;/book> & lt;/root>首先遍历一下该xml文档
& lt; php ? $ doc=新DOMDocument (); $ doc→负载(& # 39;example.xml& # 39;); 书=$ doc→美元getElementsByTagName (“book");//遍历 foreach(书书美元){ echo $书→getAttribute (& # 39; id # 39;) !”产生绯闻;; echo $书→getElementsByTagName (“title")→项目(0)→nodeValue; 回声“& lt; br>“; }运行结果为:
1-title1
2-title2
3-title3
4-title4
5-title5修改:
& lt; ?php $ doc=新DOMDocument ();$ doc→负载(& # 39;example.xml& # 39;); 书=$ doc→美元getElementsByTagName (“book");//遍历 foreach(书书美元){//将id=3的标题设置为33333 如果($书→getAttribute (& # 39; id # 39;)==3) { echo $书→getAttribute (& # 39; id # 39;) !”产生绯闻;; echo $书→getElementsByTagName (“title")→项目(0)→nodeValue=https://www.yisu.com/zixun/?3333”; 回声“
”; } }//对文件做修改后,一定要记得重新萨瓦河一下,才能修改掉原文件 $ doc ->保存(example.xml);修改之后为:
& lt; ?xml version=?.0”;编码=皍tf-8" ?祝辞& lt; root> & lt;书id=?“比; & lt; title> title1 & lt;/book> & lt;书id=?“比; & lt; title> title2 & lt;/book> & lt;书id=?“在 & lt; title> 33333 & lt;/title> & lt;/book> & lt;书id=?“比; & lt; title> title4 & lt;/book> & lt;书id=?“比; & lt; title> title5 & lt;/book> & lt;/root>删除操作:
& lt; ?php $ doc=新DOMDocument (); $ doc→负载(& # 39;example.xml& # 39;); $ root=$ doc→documentElement;//根标签 书=$ doc→美元getElementsByTagName (“book");//遍历 foreach(书书美元){//将id=4的删除 如果($书→getAttribute (& # 39; id # 39;)==4) { 根→美元作用是:美元的书); } }//对文件做修改后,一定要记得重新萨瓦河一下,才能修改掉原文件 $ doc→保存(& # 39;example.xml& # 39;);删除后的结果为:
& lt; ?xml version=?.0”;编码=皍tf-8" ?祝辞& lt; root> & lt;书id=?“比; & lt; title> title1 & lt;/book> & lt;书id=?“比; & lt; title> title2 & lt;/book> & lt;书id=?“在 & lt; title> 33333 & lt;/title> & lt;/book> & lt;书id=?“比; & lt; title> title5 & lt;/book> & lt;/root>感谢各位的阅读!关于php修改xml文件的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!
php修改xml文件的方法