XML
|
|
|
|
Exporting table to a XML file
by Christophe Faizant
Here is a function permetting to export datas provided by a database (mysql for this example) the goal beeing to include them into a XML file (this one will be automatically created).
The mysql_fetch_array function returning two items per value (like [0]=>value_x and [field_name]=>value_x ) we check the array with a conditional �if($j%2)� to keep only the wished line.
Of course, if the connection settings have already been included into the page, you just have to add a "&" before their names, when the function call them at its first line.
(file db2xml.php)
<? function db2xml($host,$user,$password,$database,$table,$xml_file)
{
$create_xml = fopen($xml_file,"w"); fwrite($create_xml,"<xml>rn<table>rn");
mysql_connect($host, $user, $password); $req = mysql_db_query($database, "select * from $table");
while($row = mysql_fetch_array($req))
{ fwrite($create_xml,"<item>rn");
for($j=0;$line=each($row);$j++)
{
if($j%2)
{ fwrite($create_xml,"<$line[0]>$line[1]</$line[0]>rn");
}
} fwrite($create_xml,"</item>rn");
} fwrite($create_xml,"</table>rn</xml>"); fclose($create_xml); mysql_free_result($req);
} ?>
You get a xml file having the value of $xml_file as name, with a content like the following lines : (note that the names of the original fields have been automatically included into the destination file as <tag></tag>.
(file table_products.xml)
<xml>
<table>
<item>
<ref>001</ref>
<name>product 1</name>
<price>195.00</price>
</item>
<item>
<ref>002</ref>
<name>product 2</name>
<price>205.00</price>
</item>
<item>
<ref>003</ref>
<name>product 3</name>
<price>45.00</price>
</item>
</table>
</xml>
|
|
|
Usage Example
|
|
|
Rate This Script
|
|
|
|