如何在 php 中获取 xml 节点的属性值


How can i get the value of attribute in of a xml node in php?

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

          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 文件看起来像

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

试试这个:

function getByPattern($pattern, $source)
{
    $dom = new DOMDocument();
    @$dom->loadHTML($source);
    $xpath = new DOMXPath($dom);
    $result = $xpath->evaluate($pattern);
    return $result;
}

你可以像(使用XPath)这样使用它:

$data = getByPattern("/regions/testclass1/presets/preset",$xml);

更新


法典:

<?php
    $xmlstr = "<?xml version='"1.0'" encoding='"UTF-8'" ?><presets><preset><name code='"default'">Default</name><createdBy>named</createdBy><icons>somethignhere</icons></preset></presets>";
    $xml = new SimpleXMLElement($xmlstr);
    $result = $xml->xpath("/presets/preset/name");
    foreach($result[0]->attributes() as $a => $b) {
        echo $a,'="',$b,"'"'n";
    }
?>

输出:

code="default"

附言并尝试接受@TJHeuvel提到的答案;这表明您尊重社区(下次社区将非常乐意为您提供更多帮助......

实际上我脑海中的问题也包括删除节点,错误地我无法添加它。 所以在我看来,这是完整的答案,如果其他人觉得这有用,我的情况。这个答案不包括 SimpleXMLElement 类,因为我尝试了多少,它并没有删除带有 unset(); 的节点。于是回到原来的位置,我终于找到了答案。这是我的代码。和它的简单!!

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);