how do i output an xml file using php - 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');

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']."'>";

Converting MySQL rows to XML with 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.)

creating custom namespaces in rss

I wish to create some custom namespaces in my rss feed.
The problem is that I have the rss feed working, but the custom namespace data does not show up. I have got it to this far but if anyone could assist in showing how to get this to work properly ( if at all) it would be greatly appreciated.
below is the code i am using to achieve this to this point.
the reason for custom naming is that I am unable to attach the data to anything else that has been already approved.
<?
//Configure the Basic information
$chan_title = "sponsor";
$chan_desc = "some sponsor data.";
$chan_link = "http://pandafc.elementfx.com/panda_app_page.php";
//$image_url = "logo.gif";
//connect to the Database
include 'connect.php';
$query = "SELECT sp_ID, sp_name, sp_about, sp_website FROM sponsors ORDER BY sp_ID DESC LIMIT 25";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) < 1) {
die("No records");
}
//Build the XML data
$items = '';
while ($row = mysql_fetch_assoc($result)) {
$item_id = $row["sp_ID"];
$item_title = $row["sp_name"];
$item_link = $row["sp_about"];
$item_desc = $row["sp_website"];
$items .= <<<ITEM
<item>
<title>$item_id</title>
<sponsor:sponsor>$item_title</sponsor:sponsor>
<sponsor:about>$item_link</sponsor:about>
<sponsor:Website>$item_desc</sponsor:Website>
</item>
ITEM;
}
$content = <<<CONTENT
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:sponsor="http://pandafc.elementfx.com/nssponsor.xhtml" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>$chan_title</title>
<link>$chan_link</link>
<description>$chan_desc</description>
$items
<atom:link href="http://pandafc.elementfx.com/rssfeed1.php" />
</channel>
</rss>
CONTENT;
//print results on screen
header("Content-type: application/rss+xml");
print $content;
?>
hopefully this can be achieved and others may also find this useful

AS3. XML created from PHP needs to be send to Action Script 3

I need to make TOP 10 players table in flash. When I click button "TOP 10" it must get data from database and print list on the game screen.
What I want to make here is vision:
I have dynamically created XML from PHP and data must be sent to Action Script 3.
Here is top.php file
<?php
$time = $_POST['time'];
session_start();
$name = $_SESSION['vardas'];
$time = strtotime($time);
$times = date('s:H:i', $time);
$_SESSION['test'] = $times;
$_SESSION['test1'] = $username;
$mysqli = new mysqli("localhost","my_db","pass","my_db");
$query = "SELECT userName,time FROM eurokos ORDER by time ASC LIMIT 10";
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
// printf(" ", $mysqli->character_set_name());
}
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<results>';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo '<user name="'.$row["userName"].'" time="'.$row["time"].'" />';
}
$result->free();
}
echo '</results>';
$mysqli->close();
?>
XML looks like:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<user name="someone" time="xxx" />
<user name="someone" time="xxx" />
[...]
</results>
And here is my Action Script code:
var myXml:XML;
function uploadTops():void
{
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("top.php"));
myLoader.addEventListener(Event.COMPLETE, processXML);
}
function processXML(e:Event):void {
myXml = new XML(e.target.data);
trace(myXml);
}
function myButton(e:MouseEvent):void
{
uploadTops();
// _message = myXml.user.*; //these lines are wrong, I donn't know how to print answer
// message_txt.text = _message;
}
I got error:
Error #1090: XML parser failure: element is malformed. when trying to trace
at MemoryGame/processXML()[C:\Users\Petras\Downloads\geraseaa\geraseaa\gerase\MemoryGame.as:570]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
Thank you for answers.
Try to open your XML file with a browser and then see its source , this way you will know what exactly wrong with your XML file.
It's possible that if you will add in your php file this line :
header('Content-Type: text/xml');
before this line:
echo '<?xml version="1.0" encoding="UTF-8"?>';
it will help

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