Output from MysSQL query to xml file - php

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

Related

Retrieve data from MYSQL and save XML

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

ERROR displaying image in php

Im my project only image name are stored to SQL So that i can display it using name and image file is stored in folder
My problem is unable to display image since i have to specify path
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = '3ss';
$userdb = 'sanoj';
$passdb = '123456';
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 * FROM `mobile` where id=50";
$result = $conn->query($sql);
// Parse returned data, and displays them
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row['id']. '/'. $row['mcat']. '/'. $row['image1']. '/'.'<li><img src=\poster\process\mobile\thumb\"',$row['image1'],'"></li>' .'/'. $row['image3']. '<br />';
}
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
You can use php variables inside the html tag. This should work:
.'<li><img src=\poster\process\mobile\thumb\$row["image1"]></li>'
It is important that you are consistent with when to use double quotes and when not to. the $row should have different quotes than the ones surrounding the html tag.

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.

PHP MYSQL XML ERROR

I have a PHP file which reads the credentials from
require("phpRequireInfo.php");
And, my problem is that it keeps giving me error whenever i were to compile it. My php file looks like this:
<?php
header("Content-type: text/xml");
require("phpRequireInfo.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ($database, $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$dbname= 'csuser';
// Set the active MySQL database
$db_selected = mysql_select_db($dbname, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM Bars ";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['Name'] );
}
echo $dom->saveXML();
?>
And the error i am getting is: "error on line 4 at column 6: XML declaration allowed only at the start of the document"
The XML File looks like this when running the PHP FILE:
http://imgur.com/SWCZ8sE
Your help will greatly be appreciated
Why does it has 3 empty lines, at the begining?
try ob_start() before require, and ob_end_clean() before echo, to avoid them
ob_start();
require("phpRequireInfo.php");
.
.
.
ob_end_clean();
echo $dom->saveXML();

Categories