如何获取PHP中xml节点的attribute值? [英] How can i get the value of attribute in of a xml node in php?

查看:474
本文介绍了如何获取PHP中xml节点的attribute值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用simplexml来读取xml文件.到目前为止,我无法获得我正在寻找的属性值.这是我的代码.

I'm using simplexml to read a xml file. So far i'm unable to get the attribute value i'm looking for. this is my code.

          if(file_exists($xmlfile)){
              $doc = new DOMDocument();
              $doc->load($xmlfile);
              $usergroup = $doc->getElementsByTagName( "preset" );
              foreach($usergroup as $group){         
                 $pname = $group->getElementsByTagName( "name" );
                 $att = 'code';
                 $name = $pname->attributes()->$att; //not working

                 $name = $pname->getAttribute('code'); //not working
                 if($name==$preset_name){
                     echo($name);
                      $group->parentNode->removeChild($group);
                 }
              }
          }

我的xml文件看起来像

and my xml file looks like

<presets>
<preset>
 <name code="default">Default</name>
  <createdBy>named</createdBy>
  <icons>somethignhere</icons>
 </preset>
</presets>

推荐答案

实际上,我脑子里的问题还包括删除一个节点,错误地我无法添加它.因此,以我的观点,这是一个完整的答案. 这个答案不包括SimpleXMLElement类,因为我努力尝试不使用unset()删除节点. .回到原来的位置,我终于找到了答案.这是我的代码. 和它简单!!!

Actually question in my head includes deleting a node as well , mistakenly i could not add it. So in my point of view this is the complete answer, i a case if someone else find this useful. This answer doesn't include SimpleXMLElement class because how hard i tried it didn't delete the node with unset(); . So back to where i was , i finally found an answer. This is my code. and its Simple!!!

if(file_exists($xmlfile)){
              $doc = new DOMDocument();
              $doc->load($xmlfile);
              $presetgroup = $doc->getElementsByTagName( "preset" );
              foreach($presetgroup as $group){       
                 $pname = $group->getElementsByTagName( "name" );
                  $pcode = $pname->item(0)->getAttribute('code');
                 if($pcode==$preset_name){
                      echo($preset_name);
                      $group->parentNode->removeChild($group);
                 }
              }
          }
        $doc->save($xmlfile);

这篇关于如何获取PHP中xml节点的attribute值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆