Skip to content

Instantly share code, notes, and snippets.

@lionrajkumar
Created June 22, 2023 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lionrajkumar/228aefa414b052abe9d456fb471547e3 to your computer and use it in GitHub Desktop.
Save lionrajkumar/228aefa414b052abe9d456fb471547e3 to your computer and use it in GitHub Desktop.
Creating Valid RSS feed by using PHP and Mysql

Creating Valid RSS feed in PHP

Mysql Table

CREATE TABLE `tbl_post` (
  `id` mediumint(8) UNSIGNED NOT NULL,
  `title` text,
  `description` text,
  `author` varchar(255) DEFAULT NULL,
  `datetime` datetime DEFAULT NULL,
  `image` varchar(150) DEFAULT NULL,
  `url` varchar(150) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.php

<?php
$conn = mysqli_connect($host, $username, $password, $dbname);;
$query = "SELECT * FROM tbl_post ORDER BY id DESC";
$result = mysqli_query($conn, $sql);

header("Content-Type: text/xml;charset=iso-8859-1");

$base_url = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];

echo "<?xml version='1.0' encoding='UTF-8' ?>" . PHP_EOL;
echo "<rss version='2.0'>".PHP_EOL;
echo "<channel>".PHP_EOL;
echo "<title>Feed Title | RSS</title>".PHP_EOL;
echo "<link>".$base_url."index.php</link>".PHP_EOL;
echo "<description>Cloud RSS</description>".PHP_EOL;
echo "<language>en-us</language>".PHP_EOL;

if (mysqli_num_rows($result) > 0) {
	while($row = mysqli_fetch_assoc($result)) {
		$publish_Date = date("D, d M Y H:i:s T", strtotime($row["datetime"]));
		$image_size_array = get_headers($base_url . "images/".$row["image"], 1);
		$image_size = $image_size_array["Content-Length"];
		$image_mime_array = getimagesize($base_url . "images/".$row["image"]);
		$image_mime = $image_mime_array["mime"];

		echo "<item xmlns:dc='ns:1'>".PHP_EOL;
		echo "<title>".$row["title"]."</title>".PHP_EOL;
		echo "<link>".$base_url."blog/".$row["url"]."/</link>".PHP_EOL;
		echo "<guid>".md5($row["id"])."</guid>".PHP_EOL;
		echo "<pubDate>".$publish_Date."</pubDate>".PHP_EOL;
		echo "<dc:creator>".$row["author"]."</dc:creator>".PHP_EOL;
		echo "<description><![CDATA[".substr($row["description"], 0, 300) ."]]></description>".PHP_EOL;
		echo "<enclosure url='images/".$row["image"]."' length='".$image_size."' type='".$image_mime."' />".PHP_EOL;
		echo "<category>PHP tutorial</category>".PHP_EOL;
		echo "</item>".PHP_EOL;
	}
} else {
  echo "0 results";
}

echo '</channel>'.PHP_EOL;
echo '</rss>'.PHP_EOL;
mysqli_close($conn);

Ref: webslesson.info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment