0

I have xml.xml file:

<employers>
<employer>
    <name>John</name>
</employer>
</employers>

How to insert new employer?

I want file xml.xml to look like:

<employers>
    <employer>
        <name>Senna</name>
    </employer>
<employer>
        <name>John</name>
    </employer>
</employers>

I used this:

$xml = simplexml_load_file("xml.xml");
$employers = new SimpleXMLElement($xml);
$employer = $xml->addChild('employer');
$employer->addAttribute('name', $c->getName());
$xml->asXML($xml);

$c->getname() is String. Is there any good practices for doing this?

6
  • Why do you parse the same file twice? Is $employers a leftover of previous trials? Commented Apr 15, 2014 at 14:57
  • Yes, sorry for parsing twice. But that makes no problem to understand what I tried. No. xml file contains more elements. $employers are used to more specify and use for arrays in php. Commented Apr 15, 2014 at 15:28
  • So, what best practices are you referring to exactly? I'm not sure I understand your question at all. Commented Apr 15, 2014 at 15:48
  • @ÁlvaroG.Vicario You are right. I answered this question, but comparing the data structures. I think by asking for "good practices", he just meant "how to achieve this". Commented Apr 15, 2014 at 15:51
  • I was thinking that there is any other way to do this. Like transforming that from php array or smth like that. Commented Apr 15, 2014 at 15:57

1 Answer 1

2

Add the name of a employer not with addAttribute() but with addChild().

Demo: http://codepad.org/Pg0C87g6

Source

$string = <<<XML
<?xml version='1.0'?>
<employers>
<employer>
    <name>John</name>
</employer>
</employers>
XML;

$xml = simplexml_load_string($string);

// before
var_dump($xml);


$employer = $xml->addChild('employer');
$employer->addChild('name', 'TEST PERSON'); // $c->getName()

// after
var_dump($xml);

var_dump($xml->asXML());

For the insertion / appending of multiple elements, you might iterate over an array or over your objects ($c), like so:

foreach($listOfNewEmployers as $i => $name)
{
    $employer = $xml->addChild('employer');
    $employer->addChild('name', $name); // $c->getName()
}
Sign up to request clarification or add additional context in comments.

2 Comments

You're right but... I'm really confused by the question itself. The OP talks about "best practices". He doesn't mention having any issue at all and, when asked about some dubious code, he dismisses it as irrelevant.
The new elements are appended in memory, so you would just save the modified xml structure to a file, like file_put_contents('newXML.xml', $xml->asXML());

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.