Online Snippets Library

Save Rss Feed in to MySQL database using PHP

Some times We need to Save Rss feed in to MySQL database.To save XML in to database using PHP.we will use "DOMDocument" funtion of php.

Example

First We create Table in our database.

CREATE TABLE IF NOT EXISTS rssData (id int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `description` tinytext NOT NULL, `link` tinytext NOT NULL, PRIMARY KEY (id))

Now We use following PHP code to save record in to Mysql.

<?php
$con=mysql_connect("localhost","root","") or die("E RR O R => ".mysql_error());
  if($con)
  {
     mysql_select_db("rssfeed",$con) or die("DataBase Not Exist "); 
  }
$doc = new DOMDocument();
$doc->load('http://www.cnet.com/rss/android-update/');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array ( 
'title' => mysql_real_escape_string(strip_tags($node->getElementsByTagName('title')->item(0)->nodeValue)),
'description' => mysql_real_escape_string(strip_tags($node->getElementsByTagName('description')->item(0)->nodeValue)),
'link' =>mysql_real_escape_string(strip_tags($node->getElementsByTagName('link')->item(0)->nodeValue)),
);
array_push($arrFeeds, $itemRSS);
}

// iterate xml array.
foreach ($arrFeeds as $key => $value) {
mysql_query("INSERT INTO `rssData` (`id`, `title`, `description`, `link`) VALUES (NULL, '$value[title]' , '$value[description]', '$value[link]')");
}
?>

Out Put

Array ( [0] => Array ([title] => Use your fingerprint to authorize Google Play purchases on Android 6.0 Marshmallow - CNET [desc] => Skip typing a password and set up fingerprint authentication for your Google Play purchases. [link] => http://www.cnet.com/how-to/authorize-google-play-purchases-with-your-fingerprint-on-android-marshmallowuse-your-fingerprint/#ftag=CADe34d7bf ) [1] => Array ( [title] => Let Morgan Freeman guide you to your destination - CNET [desc] => The beloved celebrity lends his voice to navigation app Waze. Here's how to put Morgan in the driver's seat. [link] => http://www.cnet.com/how-to/let-morgan-freeman-guide-you-to-your-destination/#ftag=CADe34d7bf ) [2] => Array ([title] => Get Gmail features for Yahoo and Outlook accounts on Android - CNET [desc] => ​Want the spam protection and the powerful search powers of Gmail for your other email accounts? Here's how to get it. [link] => http://www.cnet.com/how-to/get-gmail-features-for-yahoo-and-outlook-accounts-on-android/#ftag=CADe34d7bf ) )