ipave
ipave

Reputation: 1338

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.

Upvotes: 1

Views: 102

Answers (2)

iainn
iainn

Reputation: 17417

The line

$this->parser->event->fct->addAttribute('v', $fct[1]);

will always add the v attribute to the first <fct> element in the document.

You need to assign the new child element to a variable first, and then add the attributes to that directly:

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

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

$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

Upvotes: 1

Related Questions