从MySQL数据库生成RSS提要

时间:2014-02-24 00:15:58

标签: php mysql sql xml rss

以下是我的rss.php文件的代码:

<?php header("Content-type: text/xml"); ?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>

<?php
mysql_connect("localhost", "database_user", "password") or die(mysql_error()); 
mysql_select_db("database_name") or die(mysql_error()); 

$cityquery = "SELECT * FROM cities ORDER BY RAND() LIMIT 1";
$cityresult = mysql_query($cityquery);
$cityrow = mysql_fetch_row($cityresult);
$city = $cityrow[0];

$servicequery = "SELECT * FROM services ORDER BY RAND() LIMIT 1";
$serviceresult = mysql_query($servicequery);
$servicerow = mysql_fetch_row($serviceresult);
$service = $servicerow[0];
?>

<?php
$servicename = ucwords($service);
$cityname = ucwords($city);
$servicelink = str_replace(" ","-",$service);
$citylink = str_replace(" ","-",$city);
?>

<rss version="2.0">
<channel>
  <title>My Website</title>
  <link>http://local.mywebsite.com</link>
  <description>This is my description.</description>
  <pubDate><?echo date('Y/m/d H:i:s');?></pubDate>

<?php foreach( range( 1, 25 ) as $i ): ?>

<item>
    <title><?php echo $servicename; ?> in <?php echo $cityname; ?></title>
    <pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
    <link>http://local.mywebsite.com/<?php echo $servicelink; ?>/<?php echo $citylink; ?></link>
    <description><?php echo $servicename; ?> in <?php echo $cityname; ?> - <?php echo $servicename; ?> <?php echo $cityname; ?> - <?php echo $cityname; ?> <?php echo $servicename; ?> - <?php echo $cityname; ?> - <?php echo $servicename; ?></description>
</item>

<?php endforeach; ?>

</channel>
</rss>

从上面的代码中可以看出,这个RSS提要从MySQL数据库中获取城市和服务的列表。 RSS源有25个项目,问题是它们都是完全相同的项目。需要改变什么才能基本上创建一个循环,以便每个项目实际上显示与数据库不同的城市/服务?

如果有人需要明确澄清,请随时告诉我。

1 个答案:

答案 0 :(得分:1)

您可以在while循环中使用mysql_fetch_array,然后回显它们。

附加如下内容:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo $row['cityname'];
}

不推荐使用mysql_ *函数,因此您应该先查看MySQLiPDO。正确使用这些功能还可以保护您免受SQL注入和其他漏洞的侵害。