Создание RSS-лент с возможностью просмотра из браузера

(Development) · English (33,583 views)

RSS-ленты стали наиболее популярным форматом передачи материала в последнее время. Существуют десятки RSS-клиентов, аггрегаторов, настольных и онлайн-приложений для просмотра лент. Но что насчет браузеров? Каждый день я совершаю одну и ту же ошибку: жму на ссылку “RSS-лента”, и мой браузер отображает XML-содержимое ленты. Почему нельзя просмотреть ее прямо в браузере?

В этой заметке я попытаюсь создать ленту, которая будет нормально отображаться как в браузере, так и в RSS-клиенте. Я буду использовать технологию XSLT 1.0 (так как мой Firefox не поддерживает XSLT 1.1).

Для начала нам нужна RSS-лента. Я взял ее на сайте digg.com в категории “программирование” (вы можете посмотреть на нее здесь). Лента содержит некоторые дополнительные поля в секции item (см. Спецификация RSS 2.0), что будет полезно для демонстрации того, как можно расширить мой пример.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<item>
  <title>Transparent PNG Images in IE</title>
  <link>http://digg.com/programming/Transparent_PNG_Images_in_IE</link>
  <description>Fellow digg user patrickweber commented w/ this URL. A
    javascript fix that passes off a transparent PNG to DirectX to
    render so IE can render PNG's. You can also do it with CSS via:
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,
    sizingMethod=image src='imgurlhere');</description>
  <pubDate>Wed, 5 Apr 2006 02:26:44 GMT</pubDate>
  <guid isPermaLink="true">http://digg.com/programming/Transparent_PNG_Images_in_IE</guid>
  <digg:diggCount>650</digg:diggCount>
  <digg:submitter>
    <digg:username>kefs</digg:username>
    <digg:userimage>/userimages/kefs/medium.jpg</digg:userimage>
  </digg:submitter>
  <digg:submitter>kefs</digg:submitter>
  <digg:category>programming</digg:category>
  <digg:commentCount>90</digg:commentCount>
</item>

HTML-представление RSS-ленты должно содержать кнопки добавления ленты в различные онлайн-клиенты. Кроме того, необходимо предоставить пользователю краткие инструкции по использованию ленты. Мне нравятся дизайны, основанные на CSS, потому разметку страницы я размещу во внешнем CSS-файле.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
      <head>
        <title><xsl:value-of select="/rss/channel/title"/></title>
        <link rel="stylesheet" href="digg.css" type="text/css"/>
      </head>
      <xsl:apply-templates select="rss/channel"/>
    </html>
  </xsl:template>

  <xsl:template match="channel">
    <body>
      <div class="topbox">
        <p>This is a <strong>RSS-feed</strong> from the <xsl:value-of select="title"/>
          website. RSS feeds allow you to stay up to date with the latest news and
          features you want from  <xsl:value-of select="title"/>. To subscribe to it,
          you will need a News Reader or other similar device.</p>
      </div>
      <div class="contbox">
        <div class="header">
          <div class="fltl">
            <span class="subhead">Blog for: </span>
          </div>
          <a href="#" class="item">
            <img height="15" hspace="5" vspace="0" border="0" width="32" alt="RSS" src="rss_feed.gif" title="RSS " align="left"/>
            <xsl:value-of select="title"/>
          </a>
          <br class="fltclear"/>
        </div>
        <div class="mainbox">
          <div class="itembox">
            <ul>
              <xsl:apply-templates select="item"></xsl:apply-templates>
            </ul>
          </div>
          <div class="subscrbox">
            <div class="padrhsbox">
              <h2>Subscribe to this feed</h2>
              <p>You can subscribe to this RSS feed in a number of ways, including
                the following:</p>
              <ul>
                <li>Drag the orange RSS button into your News Reader</li>
                <li>Drag the URL of the RSS feed into your News Reader</li>
                <li>Cut and paste the URL of the RSS feed into your News Reader</li>
              </ul>
              <h3>One-click subscriptions</h3>
              <p>If you use one of the following web-based News Readers,
                click on the appropriate button to subscribe to the RSS feed.
              </p>
              <a href="#" onClick="window.location='http://add.my.yahoo.com/rss?url=' + window.location;return false;">
                <img height="17" width="91" vspace="3" border="0" alt="my yahoo" src="myyahoo.gif"/>
              </a><br/>
              <a href="#" onClick="window.location='http://www.bloglines.com/sub/'+ window.location;return false;">
                <img height="18" width="91" vspace="3" border="0" alt="bloglines" src="bloglines.gif"/>
              </a><br/>
              <a href="#" onClick="window.location='http://www.newsgator.com/ngs/subscriber/subext.aspx?url='+ window.location;return false;">
                <img height="17" width="91" vspace="3" border="0" alt="newsgator" src="newsgator.gif"/>
              </a><br/>
              <a href="#" onClick="window.location='http://client.pluck.com/pluckit/prompt.aspx?GCID=C12286x053&amp;a=' + window.location + '&amp;t={title}';return false;">
                <img src="pluspluck.png" vspace="3" border="0" alt="Subscribe with Pluck RSS reader"/>
              </a><br/>
              <a href="#" onClick="window.location='http://www.rojo.com/add-subscription?resource=' + window.location;return false;">
                <img src="add-to-rojo.gif" vspace="3" border="0" alt="Subscribe in Rojo"/>
              </a><br/>
              <a href="#" onClick="window.location='http://fusion.google.com/add?feedurl=' + window.location;return false;">
                <img src="add-to-google-plus.gif" vspace="3" border="0" width="104" height="17" alt="Add to Google"/>
              </a>
            </div>
          </div>
        </div>
      </div>
    </body>
  </xsl:template>

  <xsl:template match="item">
    <li>
      <a href="{link}">
        <xsl:value-of select="title"/>
      </a>
      <small> &#8212; <xsl:value-of select="pubDate"/></small>
      <br/>
      <div class="item_desc">
        <xsl:value-of select="description"/>
      </div>
    </li>
  </xsl:template>
</xsl:stylesheet>

Интегрировать XSLT-таблицу с RSS-лентой крайне просто. Просто добавьте следующую строку после <?xml ... ?>:

1
2
<?xml version="1.0"?>
<?xml-stylesheet title="XSL_formatting" type="text/xsl" href="digg.xsl"?>

В начале я дал обещание показать, как можно обрабатывать специальные поля digg. В xsl:stylesheet необходимо добавить пространство имен digg:

1
2
3
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:digg="http://digg.com//docs/diggrss/">

Обратите внимание, что URL содержит два слеша. Теперь можно использовать атрибуты:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  <xsl:template match="item">
    <li>
      <a href="{link}">
        <xsl:value-of select="title"/>
      </a>
      <small>
        by <strong><xsl:value-of select="digg:submitter/digg:username"/></strong>
        &#8212; <xsl:value-of select="pubDate"/>
        (<xsl:value-of select="digg:diggCount"/> diggs)
      </small>
      <br/>
      <div class="item_desc">
        <xsl:value-of select="description"/>
      </div>
    </li>
  </xsl:template>

Вы можете посмотреть результаты здесь. Полные исходные коды доступны для загрузки.

Рекомендуемые книги

7 Responses to this entry

Subscribe to comments with RSS

Splurov @
said on 06.04.2006 at 7.09 · Permalink

Осталось сделать расширение для FF, которое по-умолчанию применяет к rss-лентам xslt :)

said on 06.04.2006 at 8.22 · Permalink

[...] In my previous post I’ve described how to display RSS-feed in browser using XSLT. But sometimes It’s necessary to change order of items in feed, for example sort them by date. XSLT 1.1 allows sorting by complex data types, but XSLT 1.0 does not and we need extract separate date parts. [...]

said on 25.04.2006 at 12.48 · Permalink

[...] Создание RSS-лент с возможностью просмотра из браузераВ этой заметке я попытаюсь создать ленту, которая будет нормально отображаться как в браузере, так и в RSS-клиенте. Я буду использовать технологию XSLT 1.0 (так как мой Firefox не поддерживает XSLT 1.1). [...]

said on 08.08.2006 at 13.33 · Permalink

This is amazing information. Do you know how to remove unwated tags in post data, and display everything else?
Like if there are object tags in post or javascript in post, I would like to ignore that.

said on 08.08.2006 at 14.08 · Permalink

Yeah! It’s very common needed feature, therefor it’s implemented in standard PHP library.
Check the manual for strip_tags function.

said on 08.09.2006 at 19.48 · Permalink

Is this only usable “server-side”? For example, I have a del.icio.us feed for a few bookmarks that I’d like to share between browsers. I’d like them sorted alphabetically, but I can’t seem to find a method of forcing Firefox to sort a feed how I want. The easy part is creating the transform, the hard part is forcing Firefox to use it. :) Any ideas?

said on 08.09.2006 at 20.10 · Permalink

No, on client side you can do this too :-) Just in my xslt replace template match for / with following:

1
2
3
4
5
6
7
8
9
10
  <xsl:template match="/">
    <xsl:variable name="doc" select="document('http://kpumuk.info/feed/')" />
    <html>
      <head>
        <title><xsl:value-of select="$doc/rss/channel/title"/></title>
        <link rel="stylesheet" href="digg.css" type="text/css"/>
      </head>
      <xsl:apply-templates select="$doc/rss/channel"/>
    </html>
  </xsl:template>

Comments are closed

Comments for this entry are closed for a while. If you have anything to say – use a contact form. Thank you for your patience.