How to change attribute on a simpleXML element?

2019-07-02 12:26发布

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?

4条回答
虎瘦雄心在
2楼-- · 2019-07-02 12:38

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>
查看更多
走好不送
3楼-- · 2019-07-02 12:47

Untested, but should work:

$element->attributes()->data = ((string) $element->attributes()->data) . ',ghi';
查看更多
趁早两清
4楼-- · 2019-07-02 12:54

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);
    }
}
查看更多
贪生不怕死
5楼-- · 2019-07-02 12:56

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

查看更多
登录 后发表回答