Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Thursday, April 14, 2011

Generate RSS Feed with PHP

Hi,

If you are looking for code to generate RSS via PHP, then I guess you already know what RSS is. So I am coming straight to the source code for generating it. In my example below, I am generating a RSS feed for the listing details of vaiours movies, which would contain, the movie name, image, description and a link to the details page of the particular movie.

I am keeping a database table for storing the details of the various movies. The table schema is as follows:

CREATE TABLE IF NOT EXISTS `rss` (
  `id` int(10) NOT NULL auto_increment,
  `movie_name` varchar(100) collate latin1_general_ci default NULL,
  `category` varchar(50) collate latin1_general_ci default NULL,
  `pic` varchar(50) collate latin1_general_ci default NULL,
  `link` varchar(100) collate latin1_general_ci default NULL,
  `description` varchar(300) collate latin1_general_ci default NULL,
  PRIMARY KEY  (`id`)
)

As you see in the above schema, I have categorized the various movies. This will make it more dynamic. Now before going into the actual code and its explanation, lets see how the RSS feed looks like:



Code & Explanation:

First I have created a simple .htaccess file, for URL rewriting. My idea was, user will have the category_name.xml as the URL and the list will come according the category name. Here is the htaccess:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.xml$ example.php?q=$1 [QSA,L]

In the above, all the url's ending with XML will be sent to example.php and the xml file name as the query string i.e. "?q="

Now coming to the code. The file example.php does all the hard work with the following:

First the database connection is build and the SQL query as:

<?php
mysql_connect("localhost","root");
mysql_select_db("test");

Tuesday, March 1, 2011

Parse XML with PHP

Hi,

Parsing XML have been a headache for quit a few programmers, including me ;) . So in this post I will give a very simple approach to achieve it. First let us consider an XML file, "simple.xml" with the following content:


<products>
 <product>
  <name>iPhone</name>
  <currency>$</currency>
  <price>199.99</price>
 </product>
 <product>
  <name>Galaxy Tab</name>
  <currency>$</currency>
  <price>299.99</price>
 </product>
</products>

Our motive is to navigate through each product and display their details in a listed format such as:



During such parsing all you have to do is to use getElementsByTagName() function smartly. Here there is only 1 "products" tab but multiple "product" tag. So we need to run the loop on the "product" tag.

Here is how I have had done this. Create another file, "example.php" with the following: