如果有人将链接输入到文本输入字段并按“提交”以获取实时内容,我如何将RSS提要保存到数据库?对不起我的英语很差
<?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>";
}
}
?>
我应该如何修改它才能完成它? 上面的代码完成了从已发布的RSS URL获取内容并将其显示给用户的事情。
答案 0 :(得分:1)
这段代码只是为了让你开始,考虑这是执行与你拥有的项目一样多的插入,一个更好的替代方法是做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();
答案 1 :(得分:0)
这取决于您想要在数据库中采用的方法,如果您不需要在Feed中搜索特定元素,您甚至可以将整个内容保存为单个blob