-2

Possible Duplicate:
A simple program to CRUD node and node values of xml file

This is an example XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<notes>
   <note>
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
   </note>
</notes>

How to add another note (with all its elements) using SimpleXML?
addChild() adds only a child to an existing tree, as far as I know.

Community
  • 1
  • 1
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

1 Answers1

0

Well, first I'd get a better reference. Maybe the PHP manual, which is a great resource:

http://www.php.net/manual/en/simplexml.examples-basic.php#example-5118

This adds a node to your notes list:

<?php

$notesxml = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<notes>
   <note>
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
   </note>
</notes>
XML;

$notes = new SimpleXMLElement($notesxml);

$note = $notes->addChild('note');
$note->addChild('to', 'Yourself');
$note->addChild('from', 'Billy Brown');
$note->addChild('heading', 'Another note');
$note->addChild('body', 'This is the body');

echo $notes->asXML();

?>

http://codepad.org/QrlU5CYm

You are looking at the right one. You just have to load the XML first, in whatever form it comes in.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • Thank you, but I have an existing file, so I need to load it first, instead of creating a new one. Do you also have an example? – Evgenij Reznik Jun 17 '12 at 13:04
  • 1
    Wow Jared took the time to write you such a nice answer, and you just keep on pushing asking for more code? @Jared: Why not deleting the answer? And then pass me a link to one of your earlier answer I can put a bounty on? – hakre Jun 17 '12 at 13:07
  • @user1170330 - You've got three guesses which one of [these functions](http://www.php.net/manual/en/ref.simplexml.php) is the right one, but one guess should suffice. – Jared Farrish Jun 17 '12 at 13:13
  • @hakre - Spoonfed For Life is the new Yoga position. It comes very easy for some. – Jared Farrish Jun 17 '12 at 13:15
  • @JaredFarrish: Yay, joga is cool. – hakre Jun 17 '12 at 15:35
  • @hakre - No no, joga is the new [Ook!](http://esolangs.org/wiki/Ook!). It's all [perfectly logical](http://www.urbandictionary.com/define.php?term=pretzel%20logic). – Jared Farrish Jun 17 '12 at 15:37