0

If I try to add the same attribute twice to an element via simplexml, I get the following error:

Warning: SimpleXMLElement::addAttribute() [function.SimpleXMLElement-addAttribute]: Attribute already exists...

As a workaround, I'm using if-else statements for the three possibilities:

if ($a && $b) {
    $node -> addAttribute("class", "a b");
 }
 else if($a) {
    $node -> addAttribute("class", "a");
 }
 else if ($b) {
    $node -> addAttribute("class", "b");
 }

But that feels a bit clunky,and not very scalable. Is there a better way anyone is using?

1 Answer 1

2

Instead of using SimpleXMLElement::addAttribute, maybe you can just use array-access to the parameters ?

For instance, considering you have that portion of code :

$str = <<<XML
<root>
    <elem>glop</elem>
</root>
XML;

$xml = simplexml_load_string($str);
var_dump($xml->elem);

Which gives this output :

object(SimpleXMLElement)[2]
  string 'glop' (length=4)

You can add the "class=a" attribute this way :

$xml->elem['class'] .= 'a ';
var_dump($xml->elem);

Which will give you this output :

object(SimpleXMLElement)[5]
  public '@attributes' => 
    array
      'class' => string 'a ' (length=2)
  string 'glop' (length=4)

And, then, add the "class=b" attribute by concatenating that value to the existing value of class, this way :

$xml->elem['class'] .= 'b ';
var_dump($xml->elem);

And you obtain :

object(SimpleXMLElement)[7]
  public '@attributes' => 
    array
      'class' => string 'a b ' (length=4)
  string 'glop' (length=4)

Note the space at the end of the attribute's value ; maybe you'll want to clean this, using trim :

$xml->elem['class'] = trim($xml->elem['class']);
var_dump($xml->elem);

Et voila :

object(SimpleXMLElement)[8]
  public '@attributes' => 
    array
      'class' => string 'a b' (length=3)
  string 'glop' (length=4)

Hope this helps :-)

Sign up to request clarification or add additional context in comments.

1 Comment

You're my hero of the day. Awesome help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.