如何更改simpleXML元素的属性?

问题描述 投票:3回答:4

我使用SimpleXML解析XML文件:

<element data="abc,def">
 EL
</element>

但现在我想在“数据”属性上添加一些内容。不在文件中,而是在我的变量中(在我从simplexml_load_file获得的对象结构中)。

我怎样才能做到这一点?

php xml simplexml
4个回答
10
投票

未经测试,但应该工作:

$element->attributes()->data = ((string) $element->attributes()->data) . ',ghi';

1
投票

好吧,它可以像$element['data'] .= ',ghi';一样完成


1
投票

使用此更正....

class ExSimpleXMLElement extends SimpleXMLElement
{    
   function setAttribute(ExSimpleXMLElement $node, $attributeName, $attributeValue, $replace=true)
   {
        $attributes = $node->attributes();

        if (isset($attributes[$attributeName])) {
          if(!empty($attributeValue)){
            if($replace){
                $attributes->$attributeName = (string)$attributeValue;
            } else {
                $attributes->$attributeName = (string)$attributes->$attributeName.(string)$attributeValue;
            }
          } else {
            unset($attributes->$attributeName);
          }
        } else {
          $node->addAttribute($attributeName, $attributeValue);
        }
    }
}

例如:

<?php
  $xml_string = <<<XML
    <root>
        <item id="foo"/>
    </root>
  XML;

  $xml1 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
  $xml1->setAttribute($xml1, 'id', 'bar');
  echo $xml1->asXML();

  $xml2 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
  $xml2->setAttribute($xml2->item, 'id', 'bar');
  echo $xml2->asXML();

  $xml3 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
  $xml3->setAttribute($xml3->item, 'id', 'bar', false);
  echo $xml3->asXML();

  $xml4 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
  $xml4->setAttribute($xml4->item, 'id', NULL);
  echo $xml4->asXML();
?>

结果:

<?xml version="1.0"?>
<root id="bar">
    <item id="foo"/>
</root>

<?xml version="1.0"?>
<root>
     <item id="bar"/>
</root>

<?xml version="1.0"?>
<root>
      <item id="foobar"/>
</root>

<?xml version="1.0"?>
<root>
      <item/>
</root>

0
投票

您可以使用此函数(如果没有名称空间):

function setAttribute(SimpleXMLElement $node, $attributeName, $attributeValue)
{
    $attributes = $node->attributes();
    if (isset($attributes->$attributeName)) {
        $attributes->$attributeName = $attributeValue;
    } else {
        $attributes->addAttribute($attributeName, $attributeValue);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.