技术开发 频道

PHP应用实例---编写RSS系统

重要的消息

   将数据库安全的放置在其Web不可访问的目录内,下一步就是编写使用该数据库内数据连接至每个新闻信源,将其解析用于新闻数据然后展现一个定制的新闻页面的代码。

下面就是该代码usrer.php:

<?php // PHP 5 // include configuration file include('config.php'); // open database file $handle = sqlite_open($db) or die('ERROR: Unable to open database!'); // generate and execute query $query = "SELECT id, title, url, count FROM rss"; $result = sqlite_query($handle, $query) or die("ERROR: $query. ".sqlite_error_string(sqlite_last_error($handle))); // if records present if (sqlite_num_rows($result) > 0) { // iterate through resultset // fetch and parse feed while($row = sqlite_fetch_object($result)) { $xml = simplexml_load_file($row->url); echo "<h4>$row->title</h4>"; // print descriptions for ($x = 0; $x < $row->count; $x++) { // for RSS 0.91 if (isset($xml->channel->item)) { $item = $xml->channel->item[$x]; } // for RSS 1.0 elseif (isset($xml->item)) { $item = $xml->item[$x]; } echo "<a href=\"$item->link\">$item->title</a><br />$item->description<p />"; } echo "<hr />"; // reset variables unset($xml); unset($item); } } // if no records present // display message else { ?> <font size = '-1'>No feeds currently configured</font> <?php } // close connection sqlite_close($handle); ?>

   下面是一种可能的输出(请注意,在产生页面的时候会有一个时间延迟,因为PHP将会悄悄地打开到每个URL的HTTP链接以检索相应的RSS信源):
 
   完成这项工作的代码可能看上去比较简单,但实际上,在系统后台,还有很多操作正在发生。第一步就是从SQLite数据库中获取用户配置的RSS信源列表。为了达到这个目的,初始化一个SQLite数据库句柄,然后执行一个SQL SELECT查询。While()循环用于遍历该查询结果的记录集。

   对于每个因此得到的URL,使用simplexml_load_file()函数以检索和读取RSS信源。取决于所显示的信息数目,执行一个for()循环,然后解析信源中<item>元素的适当数目。请注意,访问一个<item>元素的路径根据信源是RSS 0.91还是RSS1.0而不同。
请注意,如果数据库为空,那么会出现一条错误消息。在这个例子中,既然我已经插入了一系列的记录到数据库中,所以你根本不会看到错误消息;然而,保证所有的可能发生的事情甚至细微的事情都得到解决是良好的编程习惯。

   正如之前一样,文件config.php被包含在每个脚本的顶部。该文件包含数据库访问参数,如下所示:

<?php // database details // always use a directory that cannot be accessed from the web $path = $_SERVER['DOCUMENT_ROOT'].'/../'; $db = $path.'rss.db'; ?>
0
相关文章