input
input

Reputation: 7519

insert multiple data in xml with php dom

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

Upvotes: 0

Views: 2793

Answers (1)

Gordon
Gordon

Reputation: 316989

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.

Upvotes: 2

Related Questions