The News

Чтение RSS-ленты в PHP

Термин RSS имеет много разных определений — он может быть переведен как Действительно Простая Синдикация, также он может быть переведен и по-другому, однако суть данной технологии от этого не изменится.

RSS – это передача и обновление новостей в автоматическом режиме.

Подавляющая часть новостных сайтов, блогов и т.д., публикует анонсы статей, событий, новостей в формате RSS. Он обеспечивает регулярное автоматическое обновление, так что Ваши посетители увидят самые последние и актуальные новости.

Формат RSS не предназначен для чтения человеком. Он представляет собой XML документ, специально разработанный для чтения машинами. Я уже писал про то, Как сделать RSS на сайте. А в этой статье я покажу, как читать RSS-ленту через PHP.

Но для начала, как вообще читается RSS-лента. Для чтения RSS используются специальные программы, называемые агрегаторами. Многие из них похожи на почтовые программы, но вместо входящих писем они отображают новости из различных источников (со всех новостных лент в которых вы зарегистрированы или на которые вы подписаны). Причем, как и в почте, непрочитанные новости отображаются жирным шрифтом.

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

Все современные браузеры также имеют встроенную возможность чтения RSS-ленты, однако она ограниченна.

В конечном счете, некоторые сайты собирают, агрегируют новости из различных источников на один сайт. Таким образом, осуществляется “синдикация”.

После того как RSS сервис создан пора его размещать на хостинге. Фактически RSS-лента – это ссылка подобного вида – http:/mysite.ru/rss.php, которая возвращает контент в формате XML.

Сегодня используются различные версии RSS. Так, например, RSS 2.0 – это наиболее общеупотребительный формат. Он используется для новостных сайтов и блогов, а также для размещения подкастов.

Также существует новый формат, называемый Atom, который предлагает более стандартизированный подход в обновлении XML контента. Однако он крайне мало распространен за пределами блог-сообщества. Практически все движки блогов могут генерировать Atom-ленту на лету.

Для того, чтобы читать RSS-ленту нам необходимо найти ссылку на эту самую ленту. Для этого можно зайти на сайт http://news.yandex.ru/export.html. Там выбираете категорию, которая вам понравилась, и копируете ссылку, например такую – http://news.yandex.ru/gadgets.rss.

Далее необходимо прочитать содержимое файла gadgets.rss, для этого воспользуемся встроенной в PHP функцией file_get_contents. Код далее:

$url = “http://news.yandex.ru/gadgets.rss”;
$content = file_get_contents($url);

Далее мы передаем содержимое переменной $content в конструктор класса SimpleXmlElement и получим объектное представление содержимого RSS-ленты в переменной $items.

$items = new SimpleXmlElement($content);

Итоговая функция для получения содержимого RSS-ленты будет следующая:

Читайте также:  Бот для whatsapp javascript

$url = “http://news.yandex.ru/gadgets.rss”;
$content = file_get_contents($url);
$items = new SimpleXmlElement($content);

По стандарту, RSS-лента всегда следует похожей базовой структуре: каждая лента включает в себя корневой тег “channel”. Затем каждый элемент в ленте представлен тегом channel, у которого есть свои теги:

  • link — ссылка на новость
  • title — отображаемый текст ссылки
  • description — небольшой вводный текст новости

Таким образом, сегодня мы с Вами научились разбирать RSS-ленту с помощью PHP.

Создано 26.12.2017 08:37:27

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Converting RSS to HTML

    An alternative to converting your RSS feeds to JavaScript is converting them directly to HTML pages. You can load software for this purpose onto your Web server. These software packages use various programming languages on the Web server, most often PHP.

    RSSlib

    RSSlib (www.2rss.com/software.php#rsslib) is a useful package for converting RSS feeds into HTML ( Figure 9.18 ).

    Figure 9.18. RSSlib has parsers for PHP and ASP.

    To install RSSlib, all you have to do is click the link rsslib-php.zip and unzip the file. Then copy the unzipped files over to the directory on your server where you want to use RSSlibthe same directory as the Web page in which you want the converted RSS feed to appear ( Figure 9.19 ).

    Figure 9.19. Here’s an RSSlib demo from CNET News.com.

    To get similar results for the RSS feed you choose, call the PHP script rss2html.php with the URL of the RSS feed you want to display. You pass the URL of the RSS feed using the rss_url parameter. In our example, the feed comes from USAToday.com’s top stories.

    There are various ways to insert the text for the RSS feed into a Web page; here we will simply use only HTML and the element to create floating HTML frames.

    To insert the HTML for the converted feed into a Web page, first create a 300-by-400pixel floating frame without a border or scrollbar. The element supports an element, which lets you specify the source of the floating frame’s content. And for the content in our example you would use this:

    rss2html.php?rss_url=http://www.usatoday.com/repurposing/ NewslineRss.xml

    Here’s what it looks like in a Web page:

         

    Here's the news from USA Today

    src >

    You can also position elements wherever you want them in a page by using cascading style sheet (CSS) styles. Take a look at any good HTML book for the details.

    Читайте также:  Detect If Javascript Is Disabled

    The results appear in Internet Explorer, where it looks like the RSS feed’s news items blend right into the page ( Figure 9.20 ).

    Figure 9.20. RSSlib displays USAToday.com’s news in Internet Explorer.

    Although the element used to be unique to Internet Explorer, all standard browsers support it now; you can see what this page looks like in Mozilla Firefox ( Figure 9.21 ).

    Figure 9.21. RSSlib can display USAToday.com’s news in Firefox as well.

    RSS2HTML

    RSS2HTML, a PHP-based software package that converts RSS to HTML, is a free PHP script from FeedForAll. You can download this script at www.feedforall.com/free-php-script.htm ( Figure 9.22 ).

    Figure 9.22. FeedForAll offers a free PHP script.

    To download the script, click the download link, then select the Download button. This downloads a zip file with documentation, the PHP script rss2html.php, and a sample HTML template.

    To use RSS2HTML call the rss2html.php script, passing it the parameters XMLFILE, TEMPLATE, and MAXITEMS. The XMLFILE parameter gives the name of a local RSS feed file (in the same directory as the rss2html.php script) or the URL to an RSS feed; TEMPLATE gives the name of the HTML template to use when formatting the HTML (we’ll use the sample template that comes with RSS2HTML), and MAXITEMS specifies the maximum number of items to use.

    Here’s an example; navigating to this URL displays the RSS contents of news.xml, which is the RSS feed Steve’s News:

    http://www.rssmaniac.com/rss2html/rss2html.php?XMLFILE=news.xml&TE MPLATE=sample-template.html&MAXITEMS=10

    On the other hand, you may want to embed the HTML conversion of an RSS feed in a Web page, so you can use the same technique you saw with RSSlib.

         

    Here's the news from Steve

    src >

    RSS2HTML converts the RSS feed into HTML and displays it in a floating frame ( Figure 9.23 ). Not bad.

    Figure 9.23. Here’s the page created with RSS2HTML.

    Magpie

    Magpie, at http://magpierss.sourceforge.net, is a powerful PHP-based package that lets you parse RSS and convert it into HTML ( Figure 9.24 ).

    Figure 9.24. Magpie is an XML-based RSS parser.

    You’ll have to get your hands into the PHP with Magpie, because it’s really an RSS parser, not an HTML formatter like the previous two packages. Magpie readsthat is, parsesan RSS feed and stores it in a PHP object, and you’re responsible for unpacking the feed’s data and formatting it as you want.

    Читайте также:  Https de herzen edu ru spisok program detail php id 28811

    Here’s a little PHP to read the example feed from USAToday.com’s top stories. You start PHP scripts with , and in this case, the Magpie script rss_fetch.inc is included.

    Now you can call the Magpie PHP function fetch_rss, passing it the URL of the RSS feed you want to grab.

    $url = 'http://www.usatoday.com/repurposing/NewslineRss.xml'; $rss = fetch_rss($url); . . .

    This code reads the RSS feed and stores it in the PHP variable $rss. You can display the title of the RSS feed this way:

    You can also use a PHP foreach loop to display a hyperlink for the items in the feed, each on its own line.

    If you don't know PHP, you can use this PHP script to convert RSS to HTML using Magpiejust change the feed's URL to the URL of the feed you want to use.

    Now, when you use your browser to navigate to this script, called news.php in our example, you'll see your feed in HTML form ( Figure 9.25 ). This is assuming the Magpie PHP script rss_fetch.inc is in the same directory as the news.php script.

    Figure 9.25. Here's the feed from Magpie's output of the news.php script.

    You can also embed news.php in another Web page using floating frames as before.

         

    Here's the news from USA Today

    scrolling="no" src="https://flylib.com/books/1/255/1/html/2/news.php">

    The results of this HTML appear on a page in Internet Explorer, where you can see the feed that Magpie grabbed for you ( Figure 9.26 ).

    Figure 9.26. Created with Magpie, the top-stories feed appears in Internet Explorer.

    DOMit

    The DOMit software package has a parser that can put RSS in XML DOM (Document Object Model) form ( Figure 9.27 ).

    Figure 9.27. DOMit Uses a DOM XML parser.

    XML DOM is beyond the scope of this book, but if you're an accomplished XML and PHP person, DOMit may be the package for you. The DOMit RSS parser requires the DOMit XML parser, but you can download it for free at www.engageinteractive.com/mambo/index.php?option=content&task=view&id=3665&Itemid=20233.

    You can see the DOMit RSS package at work in an example at www.engageinteractive.com/domitrss/testing_domitrss.php ( Figure 9.28 ).

    Figure 9.28. DOMit's testing interface is easy to use.

    Select an RSS feed to convert to HTML, or enter the URL of a feed and click the Parse RSS button to give you the RSS feed converted to HTML ( Figure 9.29 ).

    Figure 9.29. Here's the RSS parsed by DOMit.

    Other PHP-based RSS Converters

    RSSProcessor is an RSS converter ($79.99) that you can find at www.scientio.com/rssprocessor.aspx ( Figure 9.30 ).

    Figure 9.30. Sciento includes a link to view a site that uses RSSProcessor.

    RSSProcessor also converts multiple RSS feeds into Web page content.

    Источник

    Оцените статью