How to create XML files

If you need to create XML files in PHP, you can do it without having to create the tags yourself with strings. This code shows you how to use the new_child functions to create an XML file.

<?
$doc = new_xmldoc('1.0');
$root = $doc->add_root('members');
$member = $root->new_child('member','');

$member->new_child('lastName','John');
$member->new_child('firstName','Adams');
$member->new_child('contribution','3400');

$member = $root->new_child('member','');

$member->new_child('lastName','Debra');
$member->new_child('firstName','Hones');
$member->new_child('contribution','2400');

$member = $root->new_child('member','');

$member->new_child('lastName','Jake');
$member->new_child('firstName','Tudor');
$member->new_child('contribution','1200');

$fp = @fopen('members.xml','w');
if(!$fp) {
    die('Error cannot create XML file');
}
fwrite($fp,$doc->dumpmem());
fclose($fp);
?>

would create the following XML file.

<members>
  <member>
    <lastName>John</lastName>
    <firstName>Adams</firstName>
    <contribution>3400</contribution>
  </member>
  <member>
    <lastName>Debra</lastName>
    <firstName>Hones</firstName>
    <contribution>2400</contribution>
  </member>
  <member>
    <lastName>Jake</lastName>
    <firstName>Tudor</firstName>
    <contribution>1200</contribution>
  </member>
</members>

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.” - Jon Ribbens