php - How can I use this code to add data from multiple feeds in my Database? -
so, currently, code i'm using, enters data last feed in array namely feed4
in databse , doesn't add data other 3 feeds, how can fix this, here 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 $url) { libxml_use_internal_errors(true); $rss_doc = simplexml_load_file($url); } if (!$rss_doc) { echo "failed loading xml\n"; foreach(libxml_get_errors() $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 $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 tablename item_id = '" . $item_id . "'"; $item_exists = mysql_query($item_exists_sql, $db); if(mysql_num_rows($item_exists)<1) { $item_insert_sql = "insert 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_insert_sql, $db); echo "inserted databse successfully"; } else { } } } catch (exception $e) { echo 'caught exception: ', $e->getmessage(), "\n"; } ?>
ps: know mysql_* deprecated, production code use mysqli.
i suppose want run hole loop of script each url $all_url
. currently, finish looping on $all_url
after $rss_doc=...
. why $rss_doc
contains 'feed4', last url, , that.
move closing brace afterwards end, before catch block.
(do not confused libxml_get_errors()
contains messages urls, since got filled within foreach
loop.)
Comments
Post a Comment