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
https://forums.phpfreaks.com/topic/101285-create-xml-files-from-php/
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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.