note 56891 deleted from function.fwrite by nlopess
| From: | nlopess@php.net | Date: | Wed, 05 Oct 2005 09:16:32 +0000 |
| Subject: | note 56891 deleted from function.fwrite by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-96406@lists.php.net to get a copy of this message | ||
Note Submitter: justen doherty // phpchap at gmail dot com
----
heres a nice function for querying a mysql database and writing the results to an xml file. Props to
Mihir Shah for the initial script, i just ammended it to write to XML. could do with some validation
<?php
//Developed by -==[Mihir Shah]==- during my Project work
//Extended by Justen Doherty (phpchap@gmail.com)
//www.anotherwebdeveloper.com
//to create connection to database
$connection = mysql_connect("localhost","root", "")
or die ("could not connect to database");
//to select the database here test is the sample database come with mysql
$db = mysql_select_db("test",$connection)
or die ("Couldn't select database.");
$rs = mysql_query("SELECT * FROM
test",$connection)
or die ("invalid query");
//count the no. of columns in the table
$fcount = mysql_num_fields($rs);
//start the file name
$filename = 'test.xml';
function writeXML($rs, $fcount,$filename)
{
//open xml file for writing
$handle = fopen($filename,'w+');
//write header to xml file
fwrite($handle, header("Content-type: text/xml"));
//you can choose any name for the root element
fwrite($handle, "<result>");
//get the db result elements
while($row = mysql_fetch_array( $rs ) )
{
//write tablerow element
fwrite($handle, "<tablerow>");
//loop out the elements in the db
for($i=0; $i< $fcount; $i++)
{
//Get the name of the specified field in a result
$tag = mysql_field_name( $rs, $i );
//write element fieldname, value, close element
fwrite($handle, "<$tag>". $row[$i]. "</$tag>");
}
//close the tablerow element
fwrite($handle, "</tablerow>");
}
//close the root element
fwrite($handle, "</result>");
}
//call the function with query result, row count and xml filename
writeXML($rs, $fcount, $filename);
?>