How to change attribute on a simpleXML element?

2019-07-02 12:11发布

问题:

I parsed a XML file with SimepleXML:

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

But now I want to append something to the "data" attribute. Not in the file, but in my variables (in the object structure that I got from simplexml_load_file).

How can I do that?

回答1:

Untested, but should work:

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


回答2:

Well, it can be done like $element['data'] .= ',ghi';



回答3:

Use this corrected....

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

Exemple :

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

result:

<?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>


回答4:

You can use this function (if no namespaces):

function setAttribute(SimpleXMLElement $node, $attributeName, $attributeValue)
{
    $attributes = $node->attributes();
    if (isset($attributes->$attributeName)) {
        $attributes->$attributeName = $attributeValue;
    } else {
        $attributes->addAttribute($attributeName, $attributeValue);
    }
}