Search code examples
phpxmlattributessimplexml

Php Xml loop through addAttribute


How can I loop through addAttribute to write multiple values.

So far it looks like this:

        for($i = 0; $i < 10; $i++)
        {
            $this->title->addAttribute('names', "'".$this->Data[$i]->names.';');
        }

I get this error:

SimpleXMLElement::addAttribute(): Attribute already exists

current the xml looks like this(without the loop, with a static value name):

<button names=Tim;"/>

but I want it to look like this after the loop:

<button names=Tim;Tom;Ted"/>

how do I achieve this?


Solution

  • you can achieve this by first create an array with all your name, and then implode your array in your attribute This should work

    PHP

    $names = [];
    foreach($this->Data as $key => $value) {
        $names[] = $value->names;
    }
    $this->title->addAttribute('names', implode(';', $names));