Retrieve data from MYSQL and save XML - php

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);

Related

Output from MysSQL query to xml file

I have this code i am trying to create a sitemap from and i need some help. When i run the php file i get the output of the file on the screen but no sitemap.xml file is created, anyone know why ?
<?
$xmlfile = 'sitemap.xml';
// this variable will contain the XML sitemap that will be saved in $xmlfile
$xmlsitemap = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// Connection data (server_address, name, password, database_name)
$hostdb = 'localhost';
$userdb = 'user';
$passdb = 'ps';
$namedb = 'db';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT id, shortUrl FROM shorturl WHERE id BETWEEN 15 AND 45000";
$result = $conn->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
// Parse the result set, and add the URL in the XML structure
foreach($result as $row) {
$xmlsitemap .= '
<br><br>
<url><br>
<loc>https://website.com/'. $row['shortUrl'] .'<loc><br>
<changefreq>monthly<changefreq>
<priority>1<priority><br>
<url>
';
}
}
You have to write the content of your $xmlfile variable to a file.
Try file_put_contents('sitemap.xml', $xmlfile); after the foreach loop.
But i am wondering whether <br> works in xml

Content appended twice in the CSV file when CSV is generated using PHP button

This is my code to generate csv file.When I click php button to generate Csv file,which is filled withthe contents based on the category column from the database.But my problem here is when the contents are getting populated twice in the csv file as shown below.Please help to out where i have to modify the code so that i can get only one time populated content as shown below as expected.Thanks in advance.
createcsv.php
<?php
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stats";
define("DB_SERVER", "localhost");
define("DB_NAME", "stats");
define("DB_USER", "user");
define("DB_PASSWORD", '');
$dbconn = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
$conn = #mysql_select_db(DB_NAME,$dbconn);
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "DB connection failed";
}
// Query DB to fetch hit count for each category and in turn create corresponding .csv file
function createCSVFile($type) {
$msql = "SELECT TRIM(TRAILING '.000000' from UNIX_TIMESTAMP(hitdate)*1000) as unixdate,count from h_stats where category='".$type."' order by unixdate asc";
$query = mysql_query($msql);
$type = str_replace(' ', '', $type);
$tmp_file = "data/tmp_".$type.".csv";
$fp = fopen("$tmp_file", "w");
// Write the query contents to temp file
while($row = mysql_fetch_array($query))
{
fputcsv($fp, $row);
}
fclose($fp);
// Modify the contents of the file as per the high chart input data format
$fp = fopen("$tmp_file", 'r+');
rewind($fp);
$file = "data/".$type.".csv";
$final = fopen("$file", 'w');
while($line = fgets($fp)){
trim($line);
$line = '['.$line.'],';
fputs($final,$line);
}
// Append var $type and remove the trailing ,
$final = file_get_contents($file);
$content = 'var '.$type .'= [' . rtrim($final, ","). ']';
file_put_contents("$file",$content);
}
// Query DB to fetch success/failure count for Hits and in turn create corresponding .csv file
function createHitOutcomeCSVFile($type,$category) {
$sql = "SELECT TRIM(TRAILING '.000000' from UNIX_TIMESTAMP(hitdate)*1000) as unixdate,".$type." from h_stats where category='".$category."' order by unixdate asc";
$query = mysql_query($sql);
$tmp_file = "data/tmp_".$type."_".$category.".csv";
$fp = fopen("$tmp_file", "w");
// Write the query contents to temp file
while($row = mysql_fetch_array($query)){
fputcsv($fp, $row);
}
fclose($fp);
// Modify the contents of the file as per the high chart input data format
$fp = fopen("$tmp_file", 'r+');
rewind($fp);
$category = str_replace(' ', '', $category);
$file = "data/".$type."_".$category.".csv";
$final = fopen("$file", 'w');
while($line = fgets($fp)){
trim($line);
$line = '['.$line.'],';
fputs($final,$line);
}
// Append var $type and remove the trailing ,
$final = file_get_contents($file);
$content = 'var '.$type.'_'.$category.'= [' . rtrim($final, ","). ']';
file_put_contents("$file",$content);
}
// Invoke function to create the Hits.csv file
createCSVFile('Hits');
// Invoke function to get Three Hits csv file
createHitOutcomeCSVFile('TCount','Hits');
// Invoke function to get O2 Hits csv file
createHitOutcomeCSVFile('BCount','Login');
echo "Generated successfully";
?>
not expected csv file with twice populated data:
var Login_Hits= [[1427826600000,1427826600000,8763,8763
]]
Expected csv file as per highcharts format:
var Login_Hits= [[1427826600000,8763
]]
Try to debug it...
it will be easier than seeing typo or so...
it looks like the tmp file is already corrupted...
try to display the $row variable and the $query...
the problem may come from here...
In while loop I have used mysql_fetch_assoc instead of mysql_fetch_array at both the functions
while($row = mysql_fetch_assoc($query))
{
fputcsv($fp, $row);
}
The content is not repeating twice in the Csv file.This works try it!

Encoding Error when creating XML from PHP/MySQL query

I have the following code successfully querying and exporting dynamically from a MySQL to XML output. The only problem I am having now is that I am getting an encoding error and I have no idea how to track it down?
Here is a sample URL: http://progresstechnologies.com/xml/xmlExport.php
Code
//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "bb";
$config['mysql_pass'] = "bb";
$config['db_name'] = "db";
$config['table_name'] = "table";
//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 table WHERE ListOfficeName LIKE 'Premier%' ";
$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");
//output the XML data
echo $xml;
It looks like you are using MySQL's default latin1 charset for your database/table/column.
Solution 1: If you want the XML to be in latin1, you can fix the issue by changing
header ("Content-Type:text/xml");
to
header ("Content-Type: text/xml; charset=latin1");
Solution 2: If you want the XML in UTF-8, modify the latin1 column of your MySQL table to UTF8 using
ALTER TABLE tblname MODIFY fldname TEXT CHARACTER SET utf8;
Note: In you want to use UTF-8 by default instead of latin1 charset for your MySQL database, read this: http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html

convert tabular data (mysql) to xml using php

I have a My SQL database that has some tables. Now I want to extract the that data from a table and have it in XML format.
<?php
$username = "root";
$password = "";
$hostname = "";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password,"examples" );
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else
echo "Connected to MySQL<br>";
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = "car"."s"; //fruits
$xml .= "<$root_element>";
//execute the SQL query and return records
$result = mysqli_query($dbhandle,"SELECT id, name,year FROM cars");
if (!$result) {
printf("Error: %s\n", mysqli_error($dbhandle));
exit();
}
if(mysqli_num_rows($result)>0) {
while($result_array = mysqli_fetch_assoc($result)) {
$xml .= "<car>";
//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.="</car>";
}
}
$xml .= "</$root_element>";
//send the xml header to the browser header
("Content-Type:text/xml");
//output the XML data
echo $xml;
//fetch tha data from the database
/*while ($row = mysqli_fetch_array($result)) {
echo $row['id']." ".$row['name']." ". $row['year'];
echo"<br>";
}*/
//close the connection
mysqli_close($dbhandle);
?>
however, I got the following error.
The XML page cannot be displayed Cannot view XML input using style
sheet. Please correct the error and then click the Refresh button, or try again later.
Invalid at the top level of the document. Error processing resource 'http://.... my%20portable%20files/mysqlxml.php'. ... Connected to MySQL<br><?xml version="1.0" encoding="UTF-8"?><cars><car><id><![CDATA[1]]>...`
could you help me please.
The
echo "Connected to MySQL";
part might be interfering with the XML output. See, when outputting XML you must output xml and nothing else: no spaces, no text, nothing before the initial XML tag (then your root node, then the rest).
Also, I don't see the headers being correctly output, try:
header("Content-Type:text/xml");
And also add your encoding, if you must.
If all fails, please, post a link so we can see the output and debug the problem.

Allow users to pull temporary data then delete table data (headers remain)?

I don't know the best way to title this question but am trying to accomplish the following goal:
When a client logs into their profile, they are presented with a link to download data from an existing database in CSV format. The process works, however, I would like for this data to be 'fresh' each time they click the link so my plan was - once a user has clicked the link and downloaded the CSV file, the database table would 'erase' all of its data and start fresh (be empty) until the next set of data populated it.
My EXISTING CSV creation code:
<?php
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$table = 'tablename';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= '"'.$rowr[$j].'",';
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
any ideas?
$query = mysql_query('TRUNCATE TABLE '.$table);
or if you want to archive them
$query = mysql_query('RENAME TABLE db_name.'.$table.' TO db_name.'.$table.time());
$query = mysql_query('CREATE TABLE db_name.'.$table.' ( /* table structure */ )');
i'm extremely confused as to why the data needs to be 'fresh' and why you have a database table that can be cleared out at will.
can't you just export whatever data you want directly to a CSV and skip the whole writing-to-and-subsequently-deleting-the-db step?
I would think that whatever data you're collecting and storing in this 'temporary table' can be accumulated elsewhere, and then when they want the CSV, you can just get all the data you need at that time instead of keeping around a pointless table.

Categories