Šuška Stanislovas
Šuška Stanislovas

Reputation: 23

how to save rss feed to database from pasted URL using Php?

How do i save rss feed to database, after a person put a link in to text input field and press "Submit" to get live content? I'm sorry for my poor English

<?php
$url = "";
if(isset($_POST['submit'])){
    if($_POST['feedurl'] != ''){
        $url = $_POST['feedurl'];
    }
}

$invalidurl = false;
if (@simplexml_load_file($url)) {
    $feeds = simplexml_load_file($url);
} else {
    $invalidurl = true;
    echo "<h2>Invalid RSS feed URL.</h2>";
}


$i=0;
if (!empty($feeds)) {
    $site = $feeds->channel->title;
    $sitelink = $feeds->channel->link;

    echo "<h1>".$site."</h1>";
    foreach ($feeds->channel->item as $item) {
        $title = $item->title;
        $link = $item->link;
        $description = $item->description;
        $postDate = $item->pubDate;
        $pubDate = date('D, d M Y',strtotime($postDate));

        if($i>=5) break;
?>
<div class="post">
    <div class="post-head">
        <h2><a class="feed_title" href="<?php echo $link; ?>"><?php echo $title; ?></a></h2>
        <span><?php echo $pubDate; ?></span>
    </div>
    <div class="post-content">
        <?php echo implode(' ', array_slice(explode(' ', $description), 0, 20)) . "..."; ?> <a href="<?php echo $link; ?>">Read more</a>
    </div>
</div>
<?php
$i++;
   }
} else {
    if (!$invalidurl) {
        echo "<h2>No item found</h2>";
    }
}
?>

how i should modify this to get it done? the code above get things done to fetch content from posted RSS URL and display it to an user.

Upvotes: 2

Views: 1122

Answers (2)

lloiacono
lloiacono

Reputation: 5050

This code is just to get you started, consider that this is executing as many inserts as items you have, a much better alternative to this would be to do an insert with multiple values

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$stmt = $conn->prepare('INSERT INTO RSS_FEED (title, item, link, descripton, pub_date) VALUES (?, ?, ?, ?, ?)');

$values = array();
foreach ($feeds->channel->item as $item) {
  $stmt->bind_param(
    'sssss',
    $item->title,
    $item->link,
    $item->description,
    date('D, d M Y',strtotime($item->pubDate))
  );
  $stmt->execute();
}
$stmt->close();
$conn->close();

For more details click here

Upvotes: 2

lpezzolla
lpezzolla

Reputation: 23

It depends on the approach you want to take in the DB, if you don't need to search for particular elements inside the feeds you could even save the entire content as a single blob

Upvotes: 0

Related Questions