Page 1 of 1

Adding elements on top of xml

Posted: Wed Apr 15, 2009 3:20 am
by lammspillning
I use this code for adding elements to a xml file, but now the new element created is added last in the xml, is there a way to add it as the first element instead, and how would I do it?

Code: Select all

$xdoc = new DomDocument;
$xdoc->Load($xmlPath);
$videos = $xdoc->getElementsByTagName('videos')->item(0);
$addItem = $xdoc ->createElement('item');
$addQuestion = $xdoc ->createElement('question', $Question);
$addAnswers = $xdoc ->createElement('answers', $Answers);
$addURL = $xdoc ->createElement('url', $umaURL);
$addPosition = $xdoc ->createElement('position', $Position);
$addCountry = $xdoc ->createElement('country', $country);
$addCategory = $xdoc ->createElement('category', $category);
$videos -> appendChild($addItem);
$addItem -> appendChild($addQuestion);
$addItem -> appendChild($addAnswers);
$addItem -> appendChild($addURL);
$addItem -> appendChild($addPosition);
$addItem -> appendChild($addCountry);
$addItem -> appendChild($addCategory);
 
$saveXML = $xdoc->save($xmlPath);
 
return "New question added!"; 
 

Re: Adding elements on top of xml

Posted: Wed Apr 15, 2009 3:46 am
by requinix
It's XML. It doesn't matter.

If you really care then just rearrange the code.

Re: Adding elements on top of xml

Posted: Wed Apr 15, 2009 4:07 am
by lammspillning
ok, how do you mean?

Re: Adding elements on top of xml

Posted: Wed Apr 15, 2009 4:10 am
by requinix

Code: Select all

echo "world!";
echo "Hello ";
If you don't like the order then shuffle the lines of code around until you do.

Re: Adding elements on top of xml

Posted: Wed Apr 15, 2009 5:11 am
by susrisha

Code: Select all

 
DOMNode->insertBefore();
 
This might be what you are looking for

Re: Adding elements on top of xml

Posted: Wed Apr 15, 2009 7:23 am
by lammspillning
I guess that's what I'm looking for, but can't get it to work.. Is this how I should use it?

on line 11 in my previous code:
$videos -> appendChild($addItem->insertBefore(item[0]));

Re: Adding elements on top of xml

Posted: Wed Apr 15, 2009 11:43 am
by php_east
maybe easier if

Code: Select all

$xdoc2 = new DomDocument;
$xdoc2 = appendChild(new xml tag)
$xdoc2 = appendChild($xdoc1, deep)
 
something like that.