Idhanta Kakkar February 2016

How can I use this code to add data from multiple feeds in my Database?

So, currently, the code I'm using, only enters the data from last feed in the array namely feed4 in the databse and doesn't add the data from the other 3 feeds, how can I fix this, here is the code:

<?php

$db_hostname="";
$db_username="";
$db_password="";

$all_urls = array('feed1', 'feed2', 'feed3', 'feed4');

try
{


$db = mysql_connect($db_hostname,$db_username,$db_password);
if (!$db)
{
    die("Could not connect: " . mysql_error());
}
mysql_select_db("dbname", $db);

foreach ($all_urls as $url) {

libxml_use_internal_errors(true);
$RSS_DOC = simpleXML_load_file($url);
}
if (!$RSS_DOC) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}


$rss_title = $RSS_DOC->channel->title;
$rss_link = $RSS_DOC->channel->link;
$rss_editor = $RSS_DOC->channel->managingEditor;
$rss_copyright = $RSS_DOC->channel->copyright;
$rss_date = $RSS_DOC->channel->pubDate;
$rss_author = $RSS_DOC->channel->author;


foreach($RSS_DOC->channel->item as $RSSitem)
{

    $item_id    = md5($RSSitem->title);
    $fetch_date = date("Y-m-j G:i:s"); 
    $item_title = $RSSitem->title;
    $item_date  = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
    $item_time  = date("H:i:s", strtotime($RSSitem->pubDate));
    $item_url   = $RSSitem->link;
    $item_author = $RSSitem->author;


    $item_exists_sql = "SELECT item_id FROM tablename where item_id = '" . $item_id . "'";
    $item_exists = mysql_query($item_exists_sql, $db);
    if(mysql_num_rows($item_exists)<1)
    {
        $item_insert_sql = "INSERT INTO tablename(item_id, feed_url, item_title, item_date, item_time, item_url, item_author, fetch_date) VALUES ('" . $item_id . "', '" . $url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_time . "', '" . $item_url . "', '" . $item_author . "', '" . $fetch_date . "')";
        $insert_item = mysql_query($item_        

Answers


EdRush February 2016

I suppose you want to run the hole loop of your script for each url from $all_url. Currently, you finish looping over $all_url after $RSS_DOC=.... That is why $RSS_DOC contains 'feed4', the last url, and only that.

Move the closing brace afterwards to the end, just before your catch block.

(Do not get confused that libxml_get_errors() contains messages for all urls, since that got well filled within the foreach loop.)

Post Status

Asked in February 2016
Viewed 3,266 times
Voted 11
Answered 1 times

Search




Leave an answer