0

since i'm new to xml, i tried out the code over here, to insert data into xml, which works. But I would like to insert multiple data into xml. how would i achieve that? for example:

<root>
<no>1</no>
<activity>swimming</activity>
<date>29/7/2010</date>
<others>
   <data1>data1</data1>
   <data2>data2</data2>
   <data3>data3</data3>
   so on..
</others>
<no>2</no>
<activity>sleeping</activity>
<date>29/7/2010</date>
<others>
   <data1>data1</data1>
   <data2>data2</data2>
   <data3>data3</data3>
   so on..
</others>
</root>

index.php:

<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);

    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml', LIBXML_NOBLANKS);

    $activities = $xmldoc->firstChild->firstChild;
    if($activities != null){
            while($activities != null){
                            ?>
            <div id="xml">
                <span>
                <?php echo $activities->textContent ?> </span> <br />

            </div>
                        <?php
                        $activities = $activities->nextSibling;
            }
        }
 ?>

<body>
<form name="input" action="insert.php" method="post">
    Insert Activity:
    <input type="text" name="activity" />
    <input type="submit" value="Send" />
</form>
</body>
</html>

insert.php:

<?php
    header("Location: index.php");

    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');
    $newAct = $_POST['activity'];

    $root = $xmldoc->firstChild;
    $newElement = $xmldoc->createElement('activity');
    $root->appendChild($newElement);
    $newText = $xmldoc->createTextNode($newAct);
    $newElement->appendChild($newText);
    $xmldoc->save('sample.xml');

?>

the above code inserts only one node. i would like to know how to insert multiple nodes and child nodes

2
  • What is your question or what is not working? Please add some more explanation. Commented Jul 29, 2010 at 11:48
  • the above code inserts only one node. i would like to know how to insert multiple nodes and child nodes. Commented Jul 29, 2010 at 12:11

1 Answer 1

2

If you mean "how to insert multiple nodes at once in one method call", the answer is: it is impossible.

The approach with DOM is always the same: create a node and append it somewhere. One by one.

In your example above, you could leave out the TextNode creation and add the string content as the second argument to createNode. This would not use the automatic escaping and entity encoding though.

The only method of mass creation is DOMDocumentFragment::appendXML. This would take an arbitrary XML string for input. This is non-standard though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.