Jump to content

create xml files from PHP


ktsirig

Recommended Posts

Hello, I want to create an xml file from php. Is there a quick way of dealing with it? I used SimpleXML in order to extract data from xml files, but I only have a rather lame idea of creating xml files by hard-typing the elements myself...

like:

<root>
      <name>Jim</name>
      <age>23</age>
</root>

etc...

Link to comment
Share on other sites

example

The data (tbl_dept)

[pre]

+--------+----------+

| deptId | deptname |

+--------+----------+

|      1 | Dept A  |

|      2 | Dept B  |

|      3 | Dept C  |

+--------+----------+[/pre]

 

<?php
mysql_connect('localhost');
mysql_select_db('test2');

$sql = "SELECT deptId, deptname FROM tbl_dept";
$res = mysql_query($sql) or die (mysql_error());

$xml = fopen ('sample1.xml', 'w');
fwrite ($xml, '<?xml version="1.0" encoding="utf-8"?>'."\n");
fwrite ($xml, "<root>\n");
while ($row = mysql_fetch_assoc($res))
{
    fwrite ($xml, "<department>\n"); 
    foreach ($row as $fld => $val)
    {
        fwrite ($xml, "<$fld>$val</$fld>\n");
    }
    fwrite ($xml, "</department>\n"); 
}
fwrite ($xml, "</root>\n");
fclose ($xml);
?>

output-->
<?xml version="1.0" encoding="utf-8"?>
<root>
  <department>
    <deptId>1</deptId>
    <deptname>Dept A</deptname>
  </department>
  <department>
    <deptId>2</deptId>
    <deptname>Dept B</deptname>
  </department>
  <department>
    <deptId>3</deptId>
    <deptname>Dept C</deptname>
  </department>
</root>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.