Heim  >  Artikel  >  Backend-Entwicklung  >  php解析XML文档属性并编辑的代码

php解析XML文档属性并编辑的代码

WBOY
WBOYOriginal
2016-07-25 09:04:09947Durchsuche
  1. //读取xml
  2. $dom=new DOMDocument('1.0');
  3. $dom->load('data.xml');
  4. $em=$dom->getElementsByTagName('videos');//最外层节点
  5. $em=$em->item(0);
  6. $items=$em->getElementsByTagName('video');//节点
  7. //如果不用读取直接添加的话把下面这一段去掉即可
  8. foreach($items as $a){
  9. foreach($a->attributes as $b){//$b->nodeValue;节点属性的值$b->nodeName;节点属性的名称
  10. echo $b->nodeName;
  11. echo ":";
  12. echo $b->nodeValue;
  13. echo "
    ";
  14. }
  15. }
  16. //下面是往xml写入一行新的
  17. $t=$dom->createElement('video');//
  18. $dom->save('data.xml');
  19. ?>
复制代码

当时的xml文档:

复制代码

以下是最后改的可以修改xml文件:

  1. $doc = new DOMDocument();
  2. $doc->load('data.xml');
  3. //查找 videos 节点
  4. $root = $doc->getElementsByTagName('videos');
  5. //第一个 videos 节点
  6. $root = $root->item(0);
  7. //查找 videos 节点下的 video 节点
  8. $userid = $root->getElementsByTagName('video');
  9. //遍历所有 video 节点
  10. foreach ($userid as $rootdata)
  11. {
  12. //遍历每一个 video 节点所有属性
  13. foreach ($rootdata->attributes as $attrib)
  14. {
  15. $attribName = $attrib->nodeName; //nodeName为属性名称
  16. $attribValue = $attrib->nodeValue; //nodeValue为属性内容
  17. //查找属性名称为ip的节点内容
  18. if ($attribName =='img')
  19. {
  20. //查找属性内容为ip的节点内容
  21. if ($attribValue =='1')
  22. {
  23. //将属性为img,img内容为1的修改为image;
  24. $rootdata->setAttribute('img','image');
  25. $doc->save('data.xml');
  26. }
  27. }
  28. }
  29. }
  30. ?>
复制代码

脚本学堂 编辑推荐: php读取xml的类 php xml文档解析函数学习实例 php解析XML数据的一段代码 PHP读取XML的几种方法 php中使用DOM类读取XML文件的代码 实例学习php操作XML的类DOMDocument



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn