Sunday, January 18, 2009

PHP and XML with DOMDocument Class

XML stands for Extensible Markup Language. XML is a wonderful technique to store and transport data.Here is the example to create an XML file with PHP DOMDocument class.

$sXML = '<root><element><key>a</key><value>b</value></element></root>' ;
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->loadXML($sXML);
echo $doc->saveXML();
?>

This is another methode to create an XML file using DOMDocument class

createElement( "Music" );
$xml_track = $xml->createElement( "Track", "Karnatic" );
// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
// Create another element.
$xml_note = $xml->createElement( "Note", "Golden Melody of Subalakshmi" );
// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );
// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Hindutani" );
$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_note = $xml->createElement( "Note", "Melodies of Pandit Bheem Sen Joshi" );
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
// Parse the XML.print
$xml->saveXML();
?>

No comments:

Post a Comment