Converting MySQL rows to XML with PHP - php

I'm working on my php script to output the information from mysql database. I want to output these echo results in my php page as a xml file as i want to make it looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name></display-name>
<programme channel="" start="" stop="">
<title lang="en"></title>
<sub-title lang="en"></sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
Here's my PHP:
<?php
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypasword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = clean($_GET['channels']);
$id = clean($_GET['id']);
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
zap2it($row);
}
mysql_close();
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
echo '<?xml version=""1.0"" encoding="UTF-8" ?>';
echo '<tv generator-info-name="www.mysite.com/xmltv">';
echo '<channel id="">';
echo '<display-name></display-name>';
echo '<programme channel="" start="" stop="">';
echo '<title lang="en"></title>';
echo '<sub-title lang="en"></sub-title>';
echo '<desc lang="en"></desc>';
echo '<category lang="en"></category>';
echo '</programme>';
echo '</channel>';
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
echo "<p id='links'>";
echo "http://www.mysite.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'</p>';
}
}
}
?>
Here's what my php output looks like:
<?xml version="1.0" encoding="UTF-8" ?><tv generator-info-name="www.mysite.com/xmltv"><channel id=""><display-name></display-name><programme channel="" start="" stop=""><title lang="en"></title><sub-title lang="en"></sub-title><desc lang="en"></desc><category lang="en"></category></programme></channel>
Edit: I have got a problem with echo. I can't be able to echo for the channels in the database.
if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
}
mysql_close();
}
Here's the error I have got: error on line 12 at column 11: XML declaration allowed only at the start of the document
I will get the error when I'm using this under the while statement:
while ($row = mysql_fetch_array($result1))
{
echo '<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name></display-name>
<programme channel="" start="" stop="">
<title lang="en"></title>
<sub-title lang="en"></sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
</tv>';
}
The output for my php is show as blank page. How do you use the code to allow me to print these xml output in my php?

if channel = 0 and id = 0 your output is correct. It may not be tabbed, but it is correct to your logic.
Depending on the browser XML might show a blank page ... make sure you do view code!
You need to rethink your logic though $channel && $id and then do !$channel && !id is suspiciously odd.

It looks like you are already successfully generating XML. Your problem is that it shows up as a blank page. This is expected, because your web browser is going to interpret the XML as a bunch of HTML tags, and tags don't get displayed.
What you probably want to do is set the content type to XML so that the web browser knows it's XML and not HTML. You can do this by adding the header before you send any other output (i.e. before any echo statements):
header('Content-type: application/xml');
This is necessary because if you don't specify the content type explicitly, the server will automatically send a content type header that tells the browser that the content is HTML.
You can use your browser's debugging console (press F12 to open it in most modern browsers) to inspect the HTTP headers that your script is sending and verify that it's declaring the correct content type.
The other alternative is to format the XML as HTML. This probably isn't really desirable, because the purpose of XML is the be processed by some other client and turning it into HTML makes it useless. However, if you really want to, it can be done by putting all the XML in a string and then calling the htmlspecialchars function to format it as HTML. (This turns the < and > into HTML entities, causing them to be displayed in your browser.)

Related

MYSQL Parse to XML code

I have some problem with converting mysql to xml using php due to my lack knowledge in PHP.
I got this code from a website located here http://www.mightywebdeveloper.com/coding/mysql-to-xml-php/
<?php
header('Access-Control-Allow-Origin: *');
$oid= $_GET['oid'];
//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "thisisuser";
$config['mysql_pass'] = "thisispass";
$config['db_name'] = "mydb";
$config['table_name'] = "mail";
//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 mail WHERE oid='".$oid."' ORDER BY id ";
//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 .= "$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 work just fine after a few edit and the output goes like this.
<mails>
<mail>
<id>101221</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
<mail>
<id>101222</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
</mails>
My problem is Id like to display the array count next to the mail tag similar to something like
<mails>
<mail id="1"> <-fetched array number?
<id>101221</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
<mail id="2">
<id>101222</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
</mails>
Please help me.
Change this:
$xml .= "<".$config['table_name'].">";
To this:
$xml .= "<".$config['table_name']." id='".$result_array['id']."'>";

XML structure while creating from MySQL query in PHP (another one)

I recently asked this question,
XML structure while creating from MySQL query in PHP. I got the answer I needed but now I have a similar case that is missing just one thing.
I duplicated the code and changed as needed but the category rows are not working.
Here is my code
$xml2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$xml2 .= "\r\n";
$xml2 .= "<resources>";
$xml2 .= "<version>1</version>";
$xml2 .= "\r\n";
//select all items in table
$sql2 = "SELECT distinct category, name FROM user where user = '$user' and category is not null order by category";
$result2 = mysql_query($sql2);
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result2)>0){
while($row2 = mysql_fetch_assoc($result2)){
if(!isset($previousRow2) || !isset($previousRow2["category"]) || $previousRow2["category"] != $row2["category"])
{
$xml2 .= "\r\n";
$xml2 .= "<category title=\"" . $row["category"] . "\" />\r\n";
}
$xml2 .= "<item drawable=\"";
$xml2 .= $row2["name"];
$xml2 .= "\" />";
$xml2 .= "\r\n";
$previousRow2 = $row2;
}
}
$xml2 .= "</resources>";
This is outputting this
<category title="" />
<item drawable="bigdx_clean" />
<category title="" />
<item drawable="bluetooth" />
<item drawable="bluetooth_audio" />
<item drawable="browser" />
<item drawable="calculator" />
<item drawable="calendar" />
<item drawable="call_history" />
<item drawable="camera" />
The titles are blank though.
I'm using the same concept of the working code from other question. It's a different query so I must have something wrong with it?
$xml2 .= "<category title=\"" . $row["category"] . "\" />\r\n";
You are accessing $row["category"], but this variable is not defined anywhere. Did you mean $row2?
For what it's worth, $row2 isn't a very descriptive name for a variable. If you are looking for another variable name because $row is taken, perhaps you need to move this into another function, where $row will just be local?
If you are (inadvertently) accessing variables that do not exist, it is likely that your on-screen errors are disabled in your local PHP configuration. It is a good idea to turn these on to aid your development process - you'll find that setting in your php.ini configuration.

how do i output an xml file using php

I have a MySQL database on my website, and I would like to know how I could get an XML output via PHP of the following column channels in the table.
I want to make the xml output to something like this:
<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name>Information from database</display-name>
<programme channel="Information from database" start="" stop="">
<title lang="en"></title>
<sub-title lang="en">
</sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
Here is the php code:
<?php
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypasword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = clean($_GET['channels']);
$id = clean($_GET['id']);
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
...
}
mysql_close();
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
echo '<?xml version=""1.0"" encoding="UTF-8" ?>';
echo '<tv generator-info-name="www.mysite.com/xmltv">';
echo '<channel id="">';
echo '<display-name></display-name>';
echo '<programme channel="" start="" stop="">';
echo '<title lang="en"></title>';
echo '<sub-title lang="en"></sub-title>';
echo '<desc lang="en"></desc>';
echo '<category lang="en"></category>';
echo '</programme>';
echo '</channel>';
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
}
}
}
?>
I would really appreciate it if you could tell me how to do this. Please note; I am a complete noob at PHP and ANY supplied code will be of great help.
Edit: I'm generating an XML file to save in my web host, but I can't be able to read the XML file as I'm getting an error error on line 3 at column 1: Extra content at the end of the document.
Here's the XML output:
<?xml version="1.0" encoding="UTF-8"?>
<tv generator-info-name="www.mysite.com/xmltv"/>
<channel><display-name>Information from database</display-name><programme/><desc/></channel>
I'd suggest to use XMLWriter. http://www.php.net/manual/en/ref.xmlwriter.php.
I see you use mysql... Instead I'd suggest to use mysqli to connect to the database, instead of the deprecated mysql. It is the improved extension.
You could do something like this:
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDTD('xml');
$xml->endDTD();
$xml->startElement('tv');
$xml->startAttribute('generator-info-name');
$xml->text('www.mysite.com/xmltv');
$xml->endAttribute();
$xml->startElement('channel');
$xml->startAttribute('id');
$xml->text('');
$xml->endAttribute();
$xml->endElement();
$xml->endElement();
$xml->endElement();
header("Content-type: text/xml; charset=utf-8");
echo $xml->outputMemory();
Good luck with it :)
Here's some example code using PHP's built in classes to build an XML tree. This isn't 100% of what you're asking for, but it demonstrates how to create the structure, add children, add attributes, etc. Using this snippet, you can get there from here. I use indentation to help me keep the tree structure straight...
// create a dom document with encoding utf8
$domtree = new DOMDocument('1.0', 'UTF-8');
// create a root element of the xml tree
$tv = $domtree->createElement('tv');
//create attributes for element
$generator_info_name = $domtree->createAttribute('generator-info-name');
$generator_info_name->value = 'www.mysite.com/xmltv';
//append attribute
$tv->appendChild($generator_info_name);
// append element to the doc
$tv = $domtree->appendChild($tv);
//add a channel as a child of the root
$channel = $domtree->createElement('channel');
$channel_id = $domtree->createAttribute('id');
$channel_id->value = '""';
$channel = $tv->appendChild($channel);
//append children to channel
$channel->appendChild($domtree->createElement('display-name','Information from database'));
$channel->appendChild($domtree->createElement("programme"));
$channel->appendChild($domtree->createElement('desc'));
//finally, save the file
echo $domtree->saveXML();
$domtree->save('myChannel.xml');

rss feed not displaying

I'm trying to create a rss feed that displays all my news.
So far the code seems to be half way there because if I view page source all the content is there but nothing is showing up on the actual page.
Here is my code rss.php
<?php
ini_set('display_errors', 1);
header("Content-type: text/xml");
include("config.php");
global $NEWS;
$str = '<?xml version="1.0" encoding="utf-8"?>';
$str.= '<rss version="2.0">';
$str.='<channel>';
$sql = "SELECT * FROM $NEWS";
$result = mysql_query($sql) or die ($sql."".mysql_error());
while($row = mysql_fetch_object($result)){
$str.= '<item>';
$str.=' <a href="'.getSEOLink(13).'&article='.$row->id.'">';
$str.= '<title>'.$row->title.'</title></a>';
$str.= '<description><![CDATA['.$row->content. ']]></description>';
$str.= '</item>';
}
$str .='</channel>';
$str .='</rss>';
echo $str;
?>
Why not make use of asXML of SimpleXMLElement ?
<?php
ini_set('display_errors', 1);
include("config.php");
global $NEWS;
$str='<channel>';
$sql = "SELECT * FROM $NEWS";
$result = mysql_query($sql) or die ($sql."".mysql_error());
while($row = mysql_fetch_object($result)){
$str.= '<item>';
$str.=' <a href="'.getSEOLink(13).'&article='.$row->id.'">';
$str.= '<title>'.$row->title.'</title></a>';
$str.= '<description><![CDATA['.$row->content. ']]></description>';
$str.= '</item>';
}
$str .='</channel>';
$xml=new SimpleXMLElement($str);
echo $xml->asXML();
You are apparently generating valid XML (thus your browser is not complaining) but not valid RSS (thus feed readers won't be able to read your stuff). For instance, <a> is not a valid RSS tag and definitively not a child of <item>.
Copy the generated XML (not the PHP source code) and validate it with your favourite RSS validator (e.g. W3C Feed Validation Service).

XML(in php) parsing on iPhone

I am developing an iPhone app and I want to put some datas to UITableView.
I got an app showing several xml parser run from here.
and then, I'd separated GDataXMLParser from this project and made it run but
I have an odd problem that I can't figure out.
This is the code putting php file.
- (void)start {
self.startTimeReference = [NSDate timeIntervalSinceReferenceDate];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
self.parsedSongs = [NSMutableArray array];
NSURL *url = [NSURL URLWithString:#"http://mydomain.blabla/phpxmltest.php"];
[NSThread detachNewThreadSelector:#selector(downloadAndParse:) toTarget:self withObject:url];
}
When I make a php to xml with echo directly, like this way,
......
echo "<entry><title>this is the TEST</title><item>TEST</item></entry>";
......
iPhone app does parse this code like XML.
But when I make a php to xml with mySQL query (cause I want to make a xml items from DB), like this way,
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
$result = mysql_connect("localhost", "my ID", "my Password");
mysql_select_db("my DB");
$q = "select name, price, age, likeit, keyword from Table where category=101";
$result = mysql_query($q);
$num_rows = mysql_num_rows($result);
echo "<entry>\n";
for ($i=1; $i<=$num_rows; $i++) {
$row = mysql_fetch_assoc($result);
echo "<item>\n";
echo "<title>" . $row["name"] . "</title>\n";
echo "<category>" . $row["price"] . "</category>\n";
echo "<artist>" . $row["age"] . "</artist>\n";
echo "<album>" . $row["likeit"] . "</album>\n";
echo "<releasedate>" . $row["keyword"] . "</releasedate>\n";
echo "</item>\n";
}
echo "</entry>";
?>
iPhone app doesn't parse this code. It tells me there's no item in XML.
What is the most strange to me, is the results on Web Browser are same exactly.
When I put the url in browser, the output itself and the source(with viewing source function of browser) are exactly same. This is the source view in web browser.(Plz don't mind some encoding problem)
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<item>
<title>������ ���ĺ� ������</title>
<category>11000</category>
<artist>3</artist>
<album>0</album>
<releasedate>���ĺ� ���߱�</releasedate>
</item>
<item>
<title>���ĺ� ��������</title>
<category>18000</category>
<artist>3</artist>
<album>0</album>
<releasedate>���ĺ� ����</releasedate>
</item>
…..
I've tried hard to make it work but it's too difficult for me. I am a starter in iOS and Web Programming. Please let me know what is the problem and solution.
Thank u in advance!:D
(Plz don't mind some encoding problem)Maybe we don't mind but the xml parser probably does.
You should
set the mimetype in the http response header
set the charset in the http response header (though it's already in the xml declaration)
set mysql's client encondig to utf8 in order to receive the data utf-8 encoded
treat all the data from the database with an appropriate escape function
or even better use something like XMLWriter
and you should also print error messages as a somewhat valid xml document since you told the client that it will receive xml.
E.g. (tested only by php -l):
<?php
if ( headers_sent() ) {
die("can't set mimetype and/or charset after output has been sent to the client");
}
ini_set('default_charset', 'utf-8');
ini_set('default_mimetype', 'text/xml');
// ini_set('default_mimetype', 'application/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
$mysql = mysql_connect("localhost", "my ID", "my Password");
if ( !$mysql ) {
die('<error>database connection failed</error>');
}
if ( !mysql_select_db("my DB", $mysql) ) {
die('<error>database selection failed</error>');
}
if ( !mysql_set_charset('utf8', $mysql) ) {
die('<error>setting database selectiocharset failed</error>');
}
$q = 'SELECT name, price, age, likeit, keyword FROM Table WHERE category=101';
$result = mysql_query($q, $mysql);
if ( !$result ) {
die('<error>database query failed</error>');
}
echo "<entry>\n";
while( false!=($row=mysql_fetch_assoc($result)) ) {
echo '
<item>
<title>', htmlspecialchars($row["name"], 'utf-8'), '</title>
<category>', htmlspecialchars($row["price"], 'utf-8'), '</category>
<artist>', htmlspecialchars($row["age"], 'utf-8'), '</artist>
<album>', htmlspecialchars($row["likeit"], 'utf-8'), '"</album>
<releasedate>', htmlspecialchars($row["keyword"], 'utf-8'), '</releasedate>
</item>';
}
echo "</entry>";
?>

Categories