【问题标题】:RSS Feed with Missing Tags缺少标签的 RSS 提要
【发布时间】:2018-01-11 20:09:38
【问题描述】:

我正在开发一个非常简单的 RSS 提要。我正在做的是从数据库中提取信息并使用 PHP 将其转换为 XML。但是,当我使用 Chrome 查看代码以确保其全部显示时,我在页面顶部看到了这些错误。

这是我用来从我的数据库中提取并创建 RSS Feed 的代码。

<?php
include('connectDatabaseScript.php');
$sql = "SELECT * FROM table ORDER BY id DESC";
$query = mysql_query($sql) or die(mysql_error());

header("Content-type: text/xml"); 

echo "<?xml version='1.0' encoding='UTF-8'?> 
<rss version='2.0'>
<channel>
<title>My RSS Feed</title>
<link>http://www.mywebsite.com/rss.php</link>
<description>The description for the feed.</description>
<language>en-us</language>"; 

while($row = mysql_fetch_array($query)) {
$title=$row['title'];
$finalTitle = str_replace("&", "and", $title);
$link=$row['link'];
$newLink = str_replace("&", "&amp;", $link);
$category = $row['category'];
$date = $row['date'];
$description = $row['description'];

echo "<item> 
<title>$finalTitle</title>
<link>$newLink</link>
<description>$description</description>
<author>John Doe</author>
<pubDate>$date<pubDate>
<category>$category</category>
</item>"; 
} 
echo "</channel></rss>"; 
?>

此代码通常会卡在标题标签上。当它这样做时,它会将链接合并在一起,并且还可以合并该项目的其余部分以及它之后的其他几个项目。这是正在发生的事情的一个示例。

<item> 
<title>Title No 415: Title <item> 
<title>Title No 291: Another Title</title>
<link>http://www.mywebsite.com/post.php?id=291</link>
<description>description</description>
<author>John Doe</author>
<pubDate>Jan. 1, 2000</pubDate>
<category>Generic</category>
</item>

我已经弄清楚是什么角色导致了这种情况发生。是我拥有的某些标题中出现的“-”字符导致了问题。我一直在尝试使用 str_replace 函数将其删除。虽然我已经能够成功地将它与“&”一起使用,但它不能与“–”一起使用。是否有其他解决方案可以摆脱标题中的“-”,或者仍然可以使用 str_replace?

【问题讨论】:

    标签: php xml rss


    【解决方案1】:

    你不应该这样写你的 XML。为避免此类错误,您可以使用DOMDocument 编写您的XML,并使用saveXML 保存它。

    【讨论】:

    • 非常感谢您的回答。以后我将学习如何使用 DOMDocument 和 saveXML 来重写我的代码,以避免出现类似这样的问题。
    【解决方案2】:

    我有一些 PHP 脚本可以进行 MySQL 查询并使用它来生成 RSS 提要。 titledescription 等 RSS 元素的文本需要进行清理,以便以 XML 形式呈现。

    这里有一个函数可以做到这一点:

    function clean_text($in_text) {
        return utf8_encode(
            htmlspecialchars(
                stripslashes($in_text)));
    }
    

    我认为更简单的功能可能会解决您遇到的问题:

    function clean_text($in_text) {
        return htmlspecialchars(
                stripslashes($in_text));
    }
    

    utf8_encode() 的调用将 ISO-8859-1 字符串编码为 UTF-8,这对我来说是必要的,因为我正在处理我的数据库中的 ISO-8859-1 字符编码。 PHP 中的htmlspecialchars() 函数将 & 变为 &, 到 >。

    下面是使用函数输出一些 RSS 的语句:

    echo "<description>" . clean_text($row['description']) . "</description>";
    

    【讨论】:

    • 非常感谢您的回答。 htmlspecialchars 函数是我目前解决这个特殊问题所需要的。
    猜你喜欢
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2010-09-15
    • 1970-01-01
    相关资源
    最近更新 更多