how to create xml files via php and MySQL [duplicate] - php

This question already has answers here:
How to generate XML file dynamically using PHP?
(8 answers)
Closed 8 years ago.
I have a problem in XML files.
I searched through the internet and found lots of examples for my problem but I am not an expert on XML files and couldn't solve my problem. I want to do and XML file and work like RSS FEED. So, I am taking my data from my database and try to create the xml-code. Here what I have in my php file
(and it is not validated because of this problem: Undefined root element: channel)
<?php
include "connection.php";
//create the table with the fields
$rss_table = array();
$query = mysql_query("SELECT * FROM rssfeeds");
while($values_query = mysql_fetch_assoc($query))
{
$rss_table [] = array(
'title' => $values_query['title'],
'description' => $values_query['summary'],
'link' => $values_query['link']
);
}
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->encoding = "utf-8";
$r = $doc->createElement( "channel" );
$doc->appendChild( $r );
//$i=0;
foreach( $rss_table as $rss )
{
$b = $doc->createElement( "item" );
$title = $doc->createElement( "title" );
$title->appendChild(
$doc->createTextNode( $rss['title'] )
);
$b->appendChild( $title );
$description = $doc->createElement( "description" );
$description->appendChild(
$doc->createTextNode( $rss['description'] )
);
$b->appendChild( $description );
$link = $doc->createElement( "link" );
$link->appendChild(
$doc->createTextNode( $rss['link'] )
);
$b->appendChild( $link );
$r->appendChild( $b );
}
echo $doc->saveXML();
$doc->save("rssfeeds.xml")
?>
I want to have title - link - description
Simple one... nothing more
And here is what I get in rssfeeds.xml file:
<?xml version="1.0" encoding="utf-8"?>
<channel>
<item>
<title>winter week</title>
<description>You can come as you are! </description>
<link>http://tdm2000international.org/tdm2000international/news.php</link>
</item>
<item>
<title>Greek night</title>
<description>elliniki bradua sto magazi</description>
<link>http://tdm2000international.org/tdm2000international/news.php</link>
</item>
<item>
<title>event website</title>
<description>first of december, how is it going?</description>
<link>http://tdm2000international.org/tdm2000international/news.php</link>
</item>
</channel>
Nice format, but it has problem. I do not understand where the problem is.
Any help would be appreciated
(I also check this website for any solution, but I could not found my solution..So, sorry about this post, if it is already exist)

ok I found my one way .. I did it with FILES via php: this is the code if anyone needs help to that:
<?php
include "connection.php";
$myFile = "rss.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
$rss_txt .= '<?xml version="1.0" encoding="utf-8"?>';
$rss_txt .= "<rss version='2.0'>";
$rss_txt .= '<channel>';
$query = mysql_query("SELECT * FROM rssfeeds");
while($values_query = mysql_fetch_assoc($query))
{
$rss_txt .= '<item>';
$rss_txt .= '<title>' .$values_query['title']. '</title>';
$rss_txt .= '<link>' .$values_query['link']. '</link>';
$rss_txt .= '<description>' .$values_query['summary']. '</description>';
$rss_txt .= '</item>';
}
$rss_txt .= '</channel>';
$rss_txt .= '</rss>';
fwrite($fh, $rss_txt);
fclose($fh);
?>

Related

Parse media:content from RSS feed with PHP

I am trying to parse media:content from RSS with PHP and then show it using HTML.
I went through numerous posts on the same topic but since i'm a beginner I couldn't figure it out because the codes were different from mine.
Currently I dont’ have any line that is trying to get the image from xml.
<?php
$html = "";
$url = "url.rss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true);
for($i = 0; $i < 50; $i++){
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description;
$pubDate = $xml->channel->item[$i]->pubDate;
$author = $xml->channel->item[$i]->author;
$html .= "<a href='$link'><h3>$title</h3></a>";
$html .= "$description";
$html .= "<p>$pubDate</p>";
$html .= "<p>$author</p><hr>";
}
echo $html;
?>
This is the info I need from the XML file:
<media:content url="www.image.jpg" medium="image" type="image/jpeg" width="850" height="425" />
Thanks!
I expect the PHP file to show the media file.
Can you please give us more info?
What is the value of '$xml' after you run simplexml_load_file? (did you get the correct data?)
What error message did you get?
EDIT - according to your comment
try using
$xml->channel->item[$i]->children('media', true)->content->attributes();
The 'media' inside children is the namespace for the 'content' element.
While the boolean 'true' variable tells the parser to refer the 'media' as a namespace

Format PHP simpleXML file

Im creating simple PHP code to generate sitemap.xml file, but the problem is, that the file is unformatted. If the file was smaller, I could look at it in browser, but it has about 1,5 MB and Chrome just gives up while loading it (IE loads it and you can view it, but its lagging really hard).
I googled and tried different solutions (even from this site), but none of them worked, so Im humbly asking for your help. Also Im using the newest PHP version and my server runs on Unix based OS if thats important.
Here is code Im using (there are couple thousands (15.000+) rows in the table, so XML file is pretty long:
$xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
$xml .= "<url>";
$xml .= "<loc>MY.URL.COM/</loc>";
$xml .= "<changefreq>always</changefreq>";
$xml .= "<priority>1.00</priority>";
$xml .= "</url>";
$xml .= "<url>";
$xml .= "<loc>MY.URL.COM/upload.php</loc>";
$xml .= "<changefreq>weekly</changefreq>";
$xml .= "<priority>0.80</priority>";
$xml .= "</url>";
$select = dbquery("SELECT * FROM MY TABLE");
while ($data = dbarray($select)) {
$xml .= "<url>";
$xml .= "<loc>MY.URL.COM/?id=".$data['id']."</loc>";
$xml .= "<changefreq>daily</changefreq>";
$xml .= "<priority>0.50</priority>";
$xml .= "</url>";
}
$xml .= '</urlset>';
$sxml = new SimpleXMLElement($xml);
$dom = new DOMDocument('1.0');
$dom->formatOutput = true;
$dom->loadXML($sxml->asXML());
$dom->saveXML("sitemap.xml");
Also, every time after new page is added Im running this code to append it to sitemap file and its appending it into one row, so need to fix that too.
Im trying both codes separately, so Im sure the first one doesnt format the document at all.
$sitemap = simplexml_load_file("sitemap.xml");
$url = $sitemap->addChild('url');
$url->addChild("loc", "MY.URL.COM/?id=".$get_id['id']);
$url->addChild("changefreq", "daily");
$url->addChild("priority", "0.50");
$sitemap->asXML("sitemap.xml");
By Unreadable I mean its saved in one line like this:
<?xml version="1.0"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url><loc>MY.URL.COM?id=1</loc><changefreq>daily</changefreq><priority>0.50</priority></url><url><loc>MY.URL.COM?id=2</loc><changefreq>daily</changefreq><priority>0.50</priority></url><url><loc>MY.URL.COM?id=5</loc><changefreq>daily</changefreq><priority>0.50</priority></url><url><loc>MY.URL.COM?id=7</loc><changefreq>daily</changefreq><priority>0.50</priority></url></urlset>
Instead of:
<?xml version="1.0"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>MY.URL.COM?id=1</loc>
<changefreq>daily</changefreq>
<priority>0.50</priority>
</url>
<url>
<loc>MY.URL.COM?id=2</loc>
<changefreq>daily</changefreq>
<priority>0.50</priority>
</url>
<url>
<loc>MY.URL.COM?id=5</loc>
<changefreq>daily</changefreq>
<priority>0.50</priority>
</url>
<url>
<loc>MY.URL.COM?id=7</loc>
<changefreq>daily</changefreq>
<priority>0.50</priority>
</url>
</urlset>
**
WORKING CODE:
**
$xml = "<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'>";
$select = dbquery("SELECT * FROM MY TABLE");
while ($data = dbarray($select)) {
$xml .= "<url>";
$xml .= "<loc>MY.URL.COM/?id=".$data['id']."</loc>";
$xml .= "<changefreq>daily</changefreq>";
$xml .= "<priority>0.50</priority>";
}
$xml .= '</urlset>';
$sitemap = simplexml_load_file($xml);
$sxe = new SimpleXMLElement($xml);
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml);
$dom->save("sitemap.xml");
Code to append to existing xml file:
$sitemap = simplexml_load_file("sitemap.xml");
$url = $sitemap->addChild('url');
$url->addChild("loc", "MY.URL.COM/?id=".$get_id['id']);
$url->addChild("changefreq", "daily");
$url->addChild("priority", "0.50");
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($sitemap->asXML());
$dom->save('sitemap.xml');
Edit Start
//you don't need simplexml
// $sxml = new SimpleXMLElement($xml);
$dom = new DOMDocument('1.0');
$dom->formatOutput = true;
$dom->loadXML($xml); // can use the xml string
$dom->save("sitemap.xml"); // need to use save() rather than saveXML
Edit End
The code that you have written for the first time will do a proper formatting. Problem will arise when you add a new element/node to sitemap.xml using simplexml.
If you want a properly formatted XML, you will need to save it using DOMDocument every time, the same one that you are doing initially.
What you are doing
$sitemap = simplexml_load_file("sitemap.xml");
$url = $sitemap->addChild('url');
$url->addChild("loc", "MY.URL.COM/?id=".$get_id['id']);
$url->addChild("changefreq", "daily");
$url->addChild("priority", "0.50");
$sitemap->asXML("sitemap.xml");
Try changing it to this:
$sitemap = simplexml_load_file("sitemap.xml");
$url = $sitemap->addChild('url');
$url->addChild("loc", "MY.URL.COM/?id=".$get_id['id']);
$url->addChild("changefreq", "daily");
$url->addChild("priority", "0.50");
$dom = new DOMDocument('1.0',LIBXML_NOBLANKS);
$dom->formatOutput = true;
$dom->loadXML($sitemap->asXML());
$dom->saveXML('sitemap.xml');
Hope it helps.
One other thing to look at is if server where your code is running is Unix/Linux it'll use Unix end of lines (LF) which if viewed with Windows editors or browser may not show right as they expect (CR-LF).

Extra content at the end of the document on chrome

http://seosailor.com/beta2/articles/showrss this url give error Extra content at the end of the document on chrome
my code is this
function showrss() {
header("Content-Type: application/xml; charset=ISO-8859-1");
$query_items = "select * from articles";
$result_items = mysql_query ($query_items) or die("Some error: ".mysql_error());
$xml = '<?xml version="1.0" encoding="ISO-8859-1" ?><rss version="2.0"><channel>';
while($row = mysql_fetch_array($result_items))
{
//$des = mysql_real_escape_string($row['a_description']);
// $a_des = str_replace(']]>', ']]>',$row['a_description']);
//$a_des = strip_tags($row['a_description']);
// $a_des = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($row['a_description']));
$a_des = htmlspecialchars($row['a_description']);
$xml .= '<item>
<title>'.$row["a_title"].'</title>
<link>'.$row["a_url"].'</link>
<description>'.$a_des.'</description></item>';
} $xml .= '</channel>';
$xml .= '</rss></xml>';
echo $xml;}
That's because of the extra </xml> closing tag at the end (there is no opening <xml> tag).

updating xml file using php

hey there i have an xml file that has what i need to do is to add an event with same location name A
<timetable>
<location name="A" >
<event >
<title>EVENT TITLE </title>
<subtitle>Amman -text </subtitle>
<description>Amman -text </description>
</event>
</location>
</timetable>
so it can be like this
<timetable>
<location name="A" >
<event >
<title>EVENT TITLE </title>
<subtitle>Amman -text </subtitle>
<description>Amman -text </description>
</event>
<event >
<title>EVENT TITLE </title>
<subtitle>Amman -text </subtitle>
<description>Amman -text </description>
</event>
</location>
</timetable>
i got stuck in my php code where i want to cheack if the event is created or not if its created modify my xml with name of the event and add the new one
this is my full php inserting code `
if(isset($_GET['coname'])){
$coid = $_GET['id'];
$cname=$_GET['coname'];
$title = $_POST ['title'];
$sub = $_POST ['sub'];
$description = $_POST ['description'];
$location = $_POST ['location'];
$event = $_POST ['event'] ;
$str =$_POST ['str'] ;
$end =$_POST ['end'] ;
$topic = $_POST ['topic'] ;
$sql="INSERT INTO timeline (title,sub,description,location,event,str,end,topic,coid)
VALUES
('$title','$sub','$location','$location','$event','$str','$end','$topic','$coid')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
$q = mysqli_query($con,"SELECT * FROM timeline where coid = $coid") or die(mysqli_error());
$xml = '<timetable start="'.$st.'" end="'.$en.'" interval="'.$in.'" title="'.$da.'">';
while($r = mysqli_fetch_array($q)){
$loc=$r['topic'];
$evns=$r['str'];
$evne= $r['end'];
$xml .= '<location name="'.$loc.'" subtext=" ">';
$xml .= '<event start="'.$evns.'" end="'.$evne.'">';
$xml .= "<title>".$r['title']."</title>";
$xml .= "<subtitle>".$r['location']."</subtitle>";
$xml .= "<description>".$r['description']."</description>";
$xml .= "</event>";
$xml .= "</location>";
}
$xml .= "</timetable>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML('xml/'.$cname.'.xml'); `
Amer, rather than creating the XML from strings, I'd use the simplexml methods:
Inserting a new <event> in existing XML:
$xml = simplexml_load_string($x); // assume XML in $x
$loc = $xml->xpath("location[#name = 'A']")[0]; // select <location> with name = A
$event = $loc->addChild("event");
$event->addAttribute("start", "2013-05-20 10:00:00");
$event->addAttribute("end", "2013-05-20 14:30:00");
$event->addChild("title", "some title");
$event->addChild("subtitle", "some subtitle");
$event->addChild("description", "some description");
see it working: http://codepad.viper-7.com/12xtVD
From what I understand, you want to create a child element. This is how I would go about doing this:
PHP:
$eleone=$_POST['elementone'];
$eletwo=$_POST['elementtwo'];
$file = "verbs.xml";
$openf = fopen($file, "c+") or die ("Cannot open file");
$str = fread ($openf, filesize($file));
$xml = new DOMDocument('1.0', 'iso-8859-1');
$xml->formatOutput=TRUE;
$xml->preserveWhiteSpace = FALSE;
$xml ->loadXML($openf) or die ("There has been an error with opening the XML file. Our team has been notified and will start working to fix this problem.");
//this is the original document
echo "<xmp>OLD:\n". $xml->saveXML(). "<xmp>";
//this is how you get the document element
$root= $xml ->documentElement;
$firstnode= $root->firstChild;
//good stuff right here; how to make a node
$ori= $firstnode->childNodes->item(2);
$eleadd= $xml->createElement($elementone);
$eleaddt= $xml->createTextNode($//what gets shown in $eleadd );
$eleadd->appendChild("$idt");
If you don't want all of this, you may be able to delete some non-crucial things like the parent elements. If you need more information, http://www.phpeveryday.com/articles/PHP-XML-Adding-XML-Nodes-P414.html is the place to go, or where I found my information.

Php write XML file (to JW player)

I use the JW player to load a XML playlist. It works fine when I manually write the XML file, but not when I use php to parse...
I want it to look like this:
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/" xmlns:jwplayer="http://developer.longtailvideo.com/trac/">
<channel>
<item>
<title>Albert</title>
<media:content url="../movies/hi.mp4" />
<description></description>
<jwplayer:duration>10</jwplayer:duration>
</item>
</channel>
</rss>
The first problem is the <rss version="2.0" ...
It forces the headers to be: <?xml version="1.0"?>
The second problem is the <media:content url="" ...
How can I print out that with php ?
The third problem is how to add the end rss </rss>
My code is:
<?php
$channel = array();
$channel [] = array(
'title' => 'Albert',
'content' => 'filmer/c1.jpg',
'duration' => "10"
);
$channel [] = array(
'title' => 'Claud',
'content' => 'filmer/c2.jpg',
'duration' => "10"
);
$doc = new DOMDocument();
$doc->formatOutput = true;
$r = $doc->createElement( "channel" );
$doc->appendChild( $r );
foreach( $channel as $item )
{
$b = $doc->createElement( "item" );
$title = $doc->createElement( "title" );
$title->appendChild(
$doc->createTextNode( $item['title'] )
);
$b->appendChild( $title );
$content = $doc->createElement( "media:content" );
$content->appendChild(
$doc->createTextNode( $item['content'] )
);
$b->appendChild( $content );
$duration = $doc->createElement( "jwplayer:duration" );
$duration->appendChild(
$doc->createTextNode( $item['duration'] )
);
$b->appendChild( $duration );
$r->appendChild( $b );
}
echo $doc->saveHTML();
$doc->save("write.xml")
?>
Any ideas?
I'm a newbie in PHP/XML, sorry :/
This line: <?xml version="1.0"?> is called XML Declaration and it is optional. So whether that line is there or not should not make any difference and pose any problems as long as you use valid XML.
As RSS is based on XML, you do not need to worry about that line being there.
I hope this clarifies this part of your question.
And as Q&A normally works best with one question each, here are those other two:
remove xml version tag when a xml is created in php / PHP DomDocument output without <?xml version=“1.0” encoding=“UTF-8”?>
Generate XML with namespace URI in PHP
It's necessary to put a header before the php code in the xml to inform jwplayer what's being loaded.
header("Content-type: text/xml");

Categories