<?php
require "XML/RSS.php";
$rss = new XML_RSS("https://php.net/news.rss");
$rss->parse();
foreach ($rss->getItems() as $item) {
print_r($item);
}
?>
需安裝 PEAR XML_RSS 套件。getItems() 回傳陣列,含 title、link、description、pubDate 等欄位。
<?php
$database = "nameofthedatabase";
$dbconnect = mysql_pconnect("localhost", "dbuser", "dbpassword");
mysql_select_db($database, $dbconnect);
$query = "SELECT link, headline, description FROM `headlines` LIMIT 15";
$result = mysql_query($query, $dbconnect);
while ($line = mysql_fetch_assoc($result)) {
$return[] = $line;
}
$now = date("D, d M Y H:i:s T");
$output = '';
$output .= '';
$output .= '';
$output .= 'Our Demo RSS ';
$output .= 'https://www.example.com/RSS/RSS.php';
$output .= 'A Test RSS ';
$output .= 'en-us ';
$output .= "$now ";
$output .= "$now ";
$output .= 'https://someurl.com ';
$output .= 'you@youremail.com ';
$output .= 'you@youremail.com ';
foreach ($return as $line) {
$output .= '- ';
$output .= '
' . htmlentities($line['headline']) . ' ';
$output .= '' . htmlentities($line['link']) . '';
$output .= '' . htmlentities(strip_tags($line['description'])) . ' ';
$output .= ' ';
}
$output .= ' ';
header("Content-Type: application/rss+xml");
echo $output;
?>
mysql_* 函式,實際專案請改用 PDO 或 mysqli。Content-Type: application/rss+xml 標頭。htmlentities() 轉義,防止 XML 格式破壞。SimplePie 解析、FeedWriter 產生)。