MYSQL Parse to XML code - php

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

Related

how to get data mysql from post view to controller | Codeigniter 3

This is part of function controller:
public function generate_google_post()
{
$query = $this->sitemap_model->get_all_products();
foreach ($query as $row) {
$xml .= '<item>
<g:id>'.$row['id'].'</g:id>
</item>';
}
echo $xml;
}
From view.php In above function I can submit to controller and generate correct XML file with data from mysql.
Issue start from here:
now I want do some customization to write xml content directly in storefront (view) and then call input data to controller and generate xml.
For this I try:
public function generate_google_post2()
{
$xml = '<channel>';
$query = $this->sitemap_model->get_all_products();
foreach ($query as $row) {
$xml .= $this->input->post('add-list');
}
$xml .= '</channel>';
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="file.xml"');
echo $xml;
}
}
and in view page I try:
<?php echo form_open('sitemap_controller/generate_google_post2'); ?>
<textarea name="add-list" id="add-list" rows="10" cols="75"> </textarea>
<button type="submit" name="process" value="generate" class="btn btn-primary pull-right" style="margin-bottom: 5px;"><?php echo trans('download_feed'); ?></button>
<?php echo form_close(); ?><!-- form end -->
and now in storefront text area form I try post:
<item>
<gid>'.$row['id'].'</gid>
</item>
XML file generate sucess but the problem is I get output XML:
<channel> <item>
<gid>'.$row['id'].'</gid>
</item> <item>
<gid>'.$row['id'].'</gid>
</item> </channel>
So missing data from mysql. Is any way post from text are and in this way get data from database and then generate to xml ?
text area view post
I try add if($_POST) then $query = $this->sitemap_model->get_all_products(); and
foreach ($query as $row) {
$xml .= $this->input->post('add-list');
}
But this not resolved this issue. Full code:
public function generate_google_post2()
{
if($_POST){
$id = $this->input->post('add-list');
$query = $this->sitemap_model->get_all_products();
$xml = '<channel>';
foreach ($query as $row) {
$xml .= $this->input->post('add-list');
}
$xml .= '</channel>';
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="file.xml"');
echo $xml;
}
}
The $row variable is being interpreted as text. You wouldn't want to do this anyway as you would be very vulnerable to malicious code submitted in the form. Essentially you are trying to provide some template to the backend to fill with data.
Provide a placeholder in your form.
<item><gid>{id}</gid></item>
In your foreach loop, replace the placeholder with your data.
$template = $this->input->post('add-list');
// Replace your placeholder
$template = str_replace('{id}', $row['id'], $template);
$template = str_replace('{title}', $row['title'], $template);
$template = str_replace('{sku}', $row['sku'], $template);
$template = str_replace('{somethingelse}', $row['thing'], $template);
$xml .= $template;
Anyone who uses this form who is not you would need to be instructed what specific text to use as the placeholder. So you would need to know, or control, what placeholders the user enters.
You could control the placeholders on the front end with buttons that insert the text on the cursor. https://jsfiddle.net/xhgk8cz7/1/

PHP output doesn't print in xml format

i have the following code.
$stmt = $conn->prepare('SELECT sponsor_path FROM sponsors WHERE conference_id = ?');
$stmt->execute(array($cid));
$sponsorsImg = $stmt->fetchall (PDO::FETCH_OBJ);
$xml_output = "<?xml version=\"1.0\" ?>";
$xml_output .= "<sponsors>";
foreach ($sponsorsImg as $spImg){
$xml_output .= "<sponsor>\n";
$xml_output .= "<image>".$spImg->sponsor_path."</image>\n";
$xml_output .= "</sponsor>\n";
}
$xml_output .= "</sponsors>";
echo $xml_output;
Instead of printing the results in xml format i get only the $spImg->sponsor_path's content in plain text. Any ideas?
Most browsers will render markup that looks like XML. So it might be the case that the XML that you want is actually produced but not displayed correctly on the browser.
Try the following:
Set the content type before outputting:
header('Content-Type: text/xml');
echo $xml_output;
If the output looks the same, then right click on the page and select view source. You should see your XML markup as intended there.

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

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

Categories