By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,825 Members | 2,437 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,825 IT Pros & Developers. It's quick & easy.

php5 and xml

P: n/a
I am trying to find a way to add a child node at the top of the node
tree. My xml document has root <songs> and child elements <song>. I need
to be able to insert <song> elements at the top not at the bottom like
appendChild.

Thanks for any help.
Jul 17 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Andrew M. wrote:
I am trying to find a way to add a child node at the top of the node
tree. My xml document has root <songs> and child elements <song>. I
need to be able to insert <song> elements at the top not at the
bottom like appendChild.


Use insertBefore, examples:

<?php

$xml = new DomDocument();

// Create and append the root node
$root = $xml->createElement("root");
$xml->appendChild($root);

// Create and add the first child
$child = $xml->createElement("song");
$child->setAttribute("number", 1);
$firstChild = $root->appendChild($child);

// Create and add another child
$child = $xml->createElement("song");
$child->setAttribute("number", 2);
$root->insertBefore($child, $firstChild);

?>

*Or*

<?php

$xml = new DomDocument();

// Create and append the root node
$root = $xml->createElement("root");
$xml->appendChild($root);

// Create and add the first child
$child = $xml->createElement("song");
$child->setAttribute("number", 1);
$root->appendChild($child);

// Create and add another child
$child = $xml->createElement("song");
$child->setAttribute("number", 2);

// Find the first song child element
$firstChild = $root->getElementsByTagName("song")->item(1);
$root->insertBefore($child, $firstChild);

?>
JW

Jul 17 '05 #2

P: n/a
Janwillem Borleffs wrote:
// Find the first song child element
$firstChild = $root->getElementsByTagName("song")->item(1);


This example is incorrect, you should get the first item:

$firstChild = $root->getElementsByTagName("song")->item(0);
JW

Jul 17 '05 #3

P: n/a
Thank you very much Janwillem. That did the trick . I had a feeling it
was insertBefore but I was having a lot of trouble tracking down
documentation about how to use it.

Janwillem Borleffs wrote:
Janwillem Borleffs wrote:
// Find the first song child element
$firstChild = $root->getElementsByTagName("song")->item(1);

This example is incorrect, you should get the first item:

$firstChild = $root->getElementsByTagName("song")->item(0);
JW

Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.