Page 1 of 1

PHP XML INSERTION

Posted: Mon Mar 21, 2011 1:35 pm
by fugix
hey guys,
Im trying to insert data into my xml file using php. I can get every working except i need to bypass the root tag. my xml file looks like this...

<playlist>
<trackList>

</trackList>
</playlist>

What i need to do is insert information between the <trackList> tags but the default is to insert the information before the <trackList> tag...right after the <playlist> tag... any thoughts on this? thank you

Re: PHP XML INSERTION

Posted: Mon Mar 21, 2011 6:47 pm
by Weiry
Are you generating the file dynamically as each page is loaded, or are you trying to edit a physical file?

Re: PHP XML INSERTION

Posted: Mon Mar 21, 2011 8:18 pm
by fugix
im trying to insert into a file that is already made..

Re: PHP XML INSERTION

Posted: Mon Mar 21, 2011 8:42 pm
by Jonah Bron
Please show your code.

Re: PHP XML INSERTION

Posted: Mon Mar 21, 2011 9:20 pm
by fugix
well my xml file is above.. and heres my php..

<?php

$mid = mysql_insert_id();
$mq = mysql_query("SELECT * FROM updates WHERE userid='".$userid."' AND id='".$mid."'");
$mrow = mysql_fetch_assoc($mq);
$mpath = $mrow['musicpath'];
$mname = $mrow['musicname'];

$filename = "/var/www/members/1/playlist.xml";
$xml = simplexml_load_file($filename);

$sxe = new SimpleXMLElement($xml->asXML());

$playlist = $sxe->addChild("trackList")->addChild("track");
$playlist->addChild("location", $mpath);
$playlist->addChild("title", $mname);
echo "<br />";

$sxe->asXML("/var/www/members/1/playlist.xml");

?>

Re: PHP XML INSERTION

Posted: Mon Mar 21, 2011 9:41 pm
by Jonah Bron
Well, first, this is redundant.

Code: Select all

$xml = simplexml_load_file($filename);

$sxe = new SimpleXMLElement($xml->asXML());
Just needs to be this:

Code: Select all

$sxe = simplexml_load_file($filename);
And, I think you want this:

Code: Select all

$playlist = $sxe->trackList->addChild("track");
Instead of this:

Code: Select all

$playlist = $sxe->addChild("trackList")->addChild("track");

Re: PHP XML INSERTION

Posted: Mon Mar 21, 2011 10:22 pm
by fugix
that worked well. Thank you