creating custom namespaces in rss - php

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

Related

xmlParseEntityRef: no name' warnings while loading xml

Hello stackoverflow community,
this code display the url for my sitemap,
the connection work correctly and display the url list (not very well)
the error code i can see in the header
This page contains the following errors:
error on line 2 at column 18210: xmlParseEntityRef: no name
Below is a rendering of the page up to the first error.
<?php
header('Content-type: application/xml; charset=utf-8') ?>
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>' ?>
<?php
define('DBHOST','localhost');
define('DBUSER','user');
define('DBNAME','database');
define('DBPWD','password');
$connect = new MySQLi(DBHOST,DBUSER,DBPWD,DBNAME)or die(mysqli_error());
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
echo '<url>';
$query = $connect->query("select * from rss");
while($row=$query->fetch_array(MYSQL_ASSOC))
{
echo '<loc>'.$row['link'].'</loc>';
}
echo '</url>';
echo '</urlset>';
?>
the code above output this (does this look correct ?)
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>http://www.exemple.com/d/brown</loc>
<loc>http://www.exemple.com/d/blue</loc>
<loc>http://www.exemple.com/d/red/</loc>
<loc>http://www.exemple.com/d/yellow</loc>
//more lines
</url></urlset>
i would like to know what i did wrong on this code
thanks you very much
(French Pierre)
i fixed the problem ,the error came from one field in the rss table contain a bad character ..., but i have added missing xml parameters
lastmod, changefreq, priority
<?php
define('DBHOST','localhost');
define('DBUSER','user');
define('DBNAME','rss');
define('DBPWD','password');
$connect = new MySQLi(DBHOST,DBUSER,DBPWD,DBNAME)or die(mysqli_error());
header("Content-Type: text/xml;charset=iso-8859-1");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
{
$query = $connect->query("select * from rss");
while($row=$query->fetch_array(MYSQL_ASSOC)) {
$url = $row["link"];
$time = $row["when"];
$lastmod = $time;
$datetime = new DateTime($lastmod);
$timeresult = $datetime->format('Y-m-d\TH:i:sP');
echo "<url>
<loc>$url</loc>
<lastmod>$timeresult</lastmod>
<changefreq>hourly</changefreq>
<priority>0.8</priority>
</url>
";}}
?>
</urlset>
like this the output does not give error anymore
it does pass google validation
thanks you

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

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

PHP + XML - how to rename and delete XML elements using SimpleXML or DOMDocument?

I've had some success due to the help of StackOverflow community to modify a complex XML source for use with jsTree. However now that I have data that is usable, it is only so if i manually edit the XML to do the following :
Rename all <user> tags to <item>
Remove some elements before the first <user> tag
insert an 'encoding=UTF-8' into the XML opener
and lastly modify the <response> (opening XML tag) to <root>
XML File Example : SampleXML
I have read and read through so many pages on here and google but cannot find a method to achieve the above items.
Point (2) I have found out that by loading it via SimpleXML and using UNSET i can delete the portions I do not require, however I am still having troubles with the rest.
I thought I could perhaps modify the source with SimpleXML (that I am more familiar with) and then continue to modify the code via the help I had been provided before.
<?php
$s = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$doc1 = simplexml_load_string($s);
unset($doc1->row);
unset($doc1->display);
#$moo = $doc1->user;
echo '<textarea>';
echo $doc1->asXML();
echo '</textarea>';
$doc = new DOMDocument();
$doc->loadXML($doc1);
$users = $doc->getElementsByTagName("user");
foreach ($users as $user)
{
if ($user->hasAttributes())
{
// create content node
$content = $user->appendChild($doc->createElement("content"));
// transform attributes into content elements
for ($i = 0; $i < $user->attributes->length; $i++)
{
$attr = $user->attributes->item($i);
if (strtolower($attr->name) != "id")
{
if ($user->removeAttribute($attr->name))
{
if($attr->name == "username") {
$content->appendChild($doc->createElement('name', $attr->value));
} else {
$content->appendChild($doc->createElement($attr->name, $attr->value));
}
$i--;
}
}
}
}
}
$doc->saveXML();
header("Content-Type: text/xml");
echo $doc->saveXML();
?>
Using recursion, you can create a brand new document based on the input, solving all your points at once:
Code
<?php
$input = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$inputDoc = new DOMDocument();
$inputDoc->loadXML($input);
$outputDoc = new DOMDocument("1.0", "utf-8");
$outputDoc->appendChild($outputDoc->createElement("root"));
function ConvertUserToItem($outputDoc, $inputNode, $outputNode)
{
if ($inputNode->hasChildNodes())
{
foreach ($inputNode->childNodes as $inputChild)
{
if (strtolower($inputChild->nodeName) == "user")
{
$outputChild = $outputDoc->createElement("item");
$outputNode->appendChild($outputChild);
// read input attributes and convert them to nodes
if ($inputChild->hasAttributes())
{
$outputContent = $outputDoc->createElement("content");
foreach ($inputChild->attributes as $attribute)
{
if (strtolower($attribute->name) != "id")
{
$outputContent->appendChild($outputDoc->createElement($attribute->name, $attribute->value));
}
else
{
$outputChild->setAttribute($attribute->name, $attribute->value);
}
}
$outputChild->appendChild($outputContent);
}
// recursive call
ConvertUserToItem($outputDoc, $inputChild, $outputChild);
}
}
}
}
ConvertUserToItem($outputDoc, $inputDoc->documentElement, $outputDoc->documentElement);
header("Content-Type: text/xml; charset=" . $outputDoc->encoding);
echo $outputDoc->saveXML();
?>
Output
<?xml version="1.0" encoding="utf-8"?>
<root>
<item id="41">
<content>
<username>bsmain</username>
<firstname>Boss</firstname>
<lastname>MyTest</lastname>
<fullname>Test Name</fullname>
<email>lalal#test.com</email>
<logins>1964</logins>
<lastseen>11/09/2012</lastseen>
</content>
<item id="61">
<content>
<username>underling</username>
<firstname>Under</firstname>
<lastname>MyTest</lastname>
<fullname>Test Name</fullname>
<email>lalal#test.com</email>
<logins>4</logins>
<lastseen>08/09/2009</lastseen>
</content>
</item>
...

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