I am completely new to PHP and I am trying to retrieve data from mysql database and store it in a xml file (and then I will create an automatic download of the file). So I have the first and the last step implemented, but I cannot store the xml data I am getting. Probably I am missing something really simple, but I have tried many things and none of them gave me the result I wanted. This is the code I am using
<?php
$file = new DOMDocument("1.0");
$file->formatOutput = true;
//database configuration
$config['host'] = "xxx";
$config['user'] = "xxx";
$config['pass'] = "xxx";
$config['db_name'] = "xxx";
$config['table_name'] = "xxx";
//connect
mysql_connect($config['host'],$config['user'],$config['pass']);
//Select
@mysql_select_db($config['db_name']);
$file = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."s";
$file .= "<$root_element>";
//All items
$sql = "SELECT * FROM ".$config['table_name'];
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$file .= "<".$config['table_name'].">";
foreach($result_array as $key => $value)
{
//$key holds the table column name
$file .= "<$key>";
$file .= "<$value>";
//and close the element
$file .= "</$key>";
}
$file.="</".$config['table_name'].">";
}
}
$file .= "</$root_element>";
//If I do an echo here with the headers, it is working.
echo $xml->saveXML();
$file->save('example.xml');
?>
Thanks for the help ;)
SOLVED: I wasn't able to make it work on the way I explained here, but I found how to skip the problem. What I did was just to create the xml in one .html/.php document and from another save the file and download using:
$xml = file_get_contents('xxxx.html');
file_put_contents('example.xml', $xml);