Search code examples
phpxmlsimplexml

Add similar attributes to similar childs SimpleXml


I need such XML:

<event id="8055107" tournament="40623">
   <fct id="1816" v="1.57" p="3" />
   <fct id="1696" v="1.2" p="3.5" />
   <fct id="703" v="9" />
   <fct id="1886" v="4.8" p="4.5"/>
   <fct id="1739" v="4.4" p="7.5"/> 
</event>

I try this but get error:

$this->parser = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><line></line>');
$this->parser->addChild('event');
$fcts = [[921, '1.5'], [922, '1.6'], [923, '1.7']];
foreach ($fcts as $fct) {
   $this->parser->event->addChild('fct')->addAttribute('id', $fct[0]);
   $this->parser->event->fct->addAttribute('v', $fct[1]);
}

The error is SimpleXMLElement::addAttribute(): Attribute already exists. Help please.


Solution

  • $this->parser->event->fct is a reference. You are trying to set attribute to the same element fct.

    The right way:

    ...
    foreach ($fcts as $fct) {
        $fct_node = $this->parser->event->addChild('fct');
        $fct_node->addAttribute('id', $fct[0]);
        $fct_node->addAttribute('v', $fct[1]);
    }
    

    http://php.net/manual/en/simplexmlelement.addchild.php