Log in

View Full Version : Dynamically Creating an XML File



patrickdaly
12-10-2008, 06:49 PM
Please bear with me. I'm a novice, but I really need to resolve this problem today. Thanks!

I'm creating an XML file via PHP using the following code:



$playlist = array();
$playlist [] = array(
'creator' => 'Example Creator',
'title' => 'Example Title',
'location' => 'http://example.com/example.flv'
);
$playlist [] = array(
'creator' => 'Example Creator 2',
'title' => 'Example Title 2',
'location' => 'http://example.com/example2.flv'
);

$doc = new DOMDocument("1.0");
$doc->formatOutput = true;

// create root element
$p = $doc->createElement( "playlist" );
$doc->appendChild( $p );

// create child element
$t = $doc->createElement("tracklist");
$p->appendChild($t);

foreach( $playlist as $track )
{
$b = $doc->createElement( "track" );

$creator = $doc->createElement( "creator" );
$creator->appendChild(
$doc->createTextNode( $track['creator'] )
);
$b->appendChild( $creator );

$title = $doc->createElement( "title" );
$title->appendChild(
$doc->createTextNode( $track['title'] )
);
$b->appendChild( $title );

$location = $doc->createElement( "location" );
$location->appendChild(
$doc->createTextNode( $track['location'] )
);
$b->appendChild( $location );

$t->appendChild( $b );
$p->appendChild( $t );

}

$doc->save("write.xml");


Despite my best efforts I can't seem to get the XML to output exactly what I need, which is this:



<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
<trackList>
<track>
<creator>Example Creator</creator>
<title>Example Title</title>
<location>http://example.com/example.flv</location>
</track>

<track>
<creator>Example Creator</creator>
<title>Example Title</title>
<location>http://example.com/example2.flv</location>
</track>
</trackList>

</playlist>


My code isn't writing the encoding (encoding="UTF-8") or the namespace (xmlns="http://xspf.org/ns/0/").

How can I add those attributes to the corresponding nodes?

Thanks for your help! :)

patrickdaly
12-10-2008, 10:26 PM
I've made some progress, but I'm not there yet...

In the previous code, lines 16-18, where I'm creating the root element, I replace it with the following code:


// create root element
$p = $doc->createElementNS( "http://xspf.org/ns/0/","playlist" );
$doc->appendChild( $p );


Now I'm getting the namespace to show up. Now I need to add the version attribute to the same line so that the XML output should be:



<playlist version="1" xmlns="http://xspf.org/ns/0/">

I've tried my hand with createAttritbute(), but just can't get it. Remember, I'm a novice!