I have table data with headings: Keyword,Search Times, Last Search,Delete and I am providing a link to download the table data in XML format .
My code is:
public function download_xml()
{
//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "user";
$config['mysql_pass'] = "password";
$config['db_name'] = "db_name";
$config['table_name'] = "tablename";
//connect to host
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
//select database
@mysql_select_db($config['db_name']) or die( "Unable to select database");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."s"; //fruits
$xml .= "<$root_element>";
//select all items in table
$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))
{
$xml .= "<".$config['table_name'].">";
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//$key holds the table column name
$xml .= "<".$key.">";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "<![CDATA[".$value."]]>";
//and close the element
$xml .= "</".$key.">";
}
$xml.="</".$config['table_name'].">";
}
}
//close the root element
$xml .= "</$root_element>";
//send the xml header to the browser
//header ("Content-Type:text/xml");
header ("Content-Type: text/xml; charset=latin1");
//output the XML data
echo $xml;
}
Linking is done by providing a link at view:
<?php echo $this->Html->link('Export to XML ',array('controller'=>'admin','action'=>'download_xml'), array('target'=>'_self'));
?>
It's giving me error:
XML Parsing Error: junk after document element
Location: http://www.abc.co.uk/admin/download_xml
Line Number 1, Column 173285:
<?xml version="1.0" encoding="UTF-8"?><search_logss><search_logs><id><![CDATA[27]]></id><keyword><![CDATA[LRG Core Collection]]></keyword><user_id><![CDATA[0]]></user_id><priority><![CDATA[30]]></priority><created><![CDATA[2014-11-28 06:57:59]]></created><modified><![CDATA[2015-04-05 09:13:21]]></modified></search_logs></search_logss><!DOCTYPE html>
------------------------------------------------------------------------------------------------------------------------------------------^
Is anyone having idea why is it so? Thanx in advance