Home Backend Development PHP Tutorial Create your own RSS client with PHP package_PHP Tutorial

Create your own RSS client with PHP package_PHP Tutorial

Jul 13, 2016 am 10:38 AM
php rss create Bag client use program Simple polymerization my own

RSS,也叫做真正简单聚合(Really Simple Syndication)或者RDF站点摘要(RDF Site Summary),是一个让Web网站向用户发布和聚合最新内容的文件格式。RSS的“feed”用XML来表示;这样做的结果是,它能够被任何具备分析XML文件的客户端读取。现在这样的RSS客户端软件很多,用于Windows和Linux平台的都有,最新版本的Mozilla Firefox和Internet Explorer都允许你订阅所需要的RSS feed,以保证你的手头总有最新的信息。

就像很多优秀的编程语言一样,PHP通过PEAR XML_RSS程序包对读取和创建RSS feed提供了支持。这个程序包是一个预先编译的代码库,它可以让你从RSS feed里提取信息,并把它们转换成另外一个格式(例如,MySQL数据库或者文本文件),或者如果你想要自定义创建一个能够从多个RSS源收集信息的Web页面。

在本文里,我将讲解后面一种情况,告诉你如何使用PEAR XML_RSS包,把来自多个RSS feed的新闻标题集成到一个Web页面上。我现在假设你已经安装好了一个工作正常的Apache和PHP,而且你已经成功地下载和安装了PEAR XML_RSS程序包和依赖关系。


开始吧

现在就让我们从一个简单的例子开始,它将告诉你XML_RSS是如何工作的。首先创建下面的脚本(列表A):

列表A

// include class
include ("RSS.php");

// download and parse RSS data
$rss =& new XML_RSS("http://techrepublic.com.com/5150-22-0.xml");
$rss->parse();

// print headlines
print_r($rss->getItems());
?>

在这里,脚本会读取类定义,然后实例化一个新的XML_RSS()对象。对象的构造函数用来传递元数据的URL——这在本文里就是TechRepublic的RSS feed。然后,调用parse()方法来分析XML和从中提取信息。最后,getItems()方法会返回一个结构清晰的嵌套数组,也就是从feed中提取出来的新闻项目。每一个项目都有一个标题、一段描述、一个发表日期,以及链接到完整文章的URL ,就像下面显示的输出一样(列表B):

列表B

Array
(
    [0] => Array
        (
            [title] => Bump the size of your information store to 75GB (Exchange 2003 Standard Edition only)
            [link] => http://techrepublic.com.com/5100-1035_11-6063252.html?
part=rss&tag=feed&subj=tr
            [description] => In Service Pack 2, the Exchange developers
have provided you with the ability to size the information store to any size you like between 1 and 75 GB, and they chose 18GB as the
default. Here's how to change the size yourself.
            [pubdate] => Fri, 21 Apr 2006 00:00:00 PDT
        )

    [1] => Array
        (
            [title] => Learn the pros and cons of Windows Firewall
            [link] => http://techrepublic.com.com/5100-1009_11-6063367.html?
part=rss&tag=feed&subj=tr
            [description] => Is Windows Firewall up to the task of securing your network? Mike Mullins has
his doubts. In this edition of Security Solutions, he delves into the details of Windows Firewall and weighs its pros and cons.
            [pubdate] => Thu, 20 Apr 2006 13:25:00 PDT
        )

...
)

提取关于feed本身的源信息也是可能的,把调用getItems()改成调用getChannelInfo()就可以了。正如其名字所表示的,这个方法用来返回与feed本身相关的信息,包括题目和描述(如果有的话)。下面就是它的代码(列表C):

列表C

// include class
include ("RSS.php");

// download and parse RSS data
$rss =& new XML_RSS("http://techrepublic.com.com/5150-22-0.xml");
$rss->parse();

// print channel information
print_r($rss->getChannelInfo());
?>

下面是输出结果(列表D):

列表D

Array
(
    [title] => TechRepublic.com
    [link] => http://www.techrepublic.com/
    [description] => Real World. Real Time.Real IT.
)

Use a single feed

As the previous example shows, XML_RSS does a pretty good job of parsing an RSS feed and converting it into a PHP array. Once this array is generated, it is fairly easy to process it into a format suitable for display on a Web site. The following example illustrates this (Listing E):

List E



The latest from TechRepublic:


    // include class
    include ("RSS.php");

    // download and parse RSS data
    $rss =& new XML_RSS("http://techrepublic.com.com/5150-22-0.xml");
    $rss->parse ();

    // print channel information
    foreach ($rss->getItems() as $item) {
    echo "

  • " . $item['title'] . "
    ";
    echo $item['description'] . " (" . $item['pubdate '] . ")

    ";
    }
    ?>



In this article, the array returned by getItems() is processed using a foreach() loop. Each element of the array is itself an array, and the elements include the news title, description, and publication date. These elements are extracted and formatted into an unsorted HTML list of elements. Figure A shows you an example of this:

Create your own RSS client with PHP package_PHP Tutorial

Array elements

Use multiple feeds

How can one feed be enough? With a little creative code you can add feeds at will! List F is such a piece of code:

List F



// include class
include ("RSS.php");

// set up array of RSS feeds
$feeds = array( "http://techrepublic.com.com/5150-22-0.xml",
                 "http://news.linux .com/news.rss",
"http://rss.slashdot.org/Slashdot/slashdot");

// retrieve each feed
// get channel information and headlines
foreach ($feeds as $f) {
$rss =& new XML_RSS($f);
$rss- >parse();
$info = $rss->getChannelInfo();
$items = $rss->getItems();

// print channel information
?>
The latest from :


    // print headlines and descriptions
    foreach ($items as $item) {
    echo "

  • " . $item['title'] . "
    ";
                                                                                                                                              . ";
    }
    ?>


}
?>


The modification to the previous example code is simple and clear. I created an array of URLs to different feeds and used a loop to process the array without hard-wired linking the URLs to the feeds in the object constructor. Each iteration of the loop creates a new XML_RSS object with a different source feed; this feed is then processed in the normal way, that is, by calling the parse() and getItems() methods. Other improvements are the use of the getChannelInfo() method, discussed earlier, which is used to dynamically display the feed's name and URL at the top of each title list.

The following is an example of the output result (Figure B):

Create your own RSS client with PHP package_PHP Tutorial

More than one RSS feed


Of course, you can modify this structure to more closely reflect your needs. For example, the script will instantly display all news headlines in each feed; for example, you can change it to only display the first 5 headlines in each feed, just use a for() loop and in the second nesting level Just use a counter. You can also reformat the page layout to display news headlines in a drop-down menu, allowing for a different type of browsing. Give it a try and have fun!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735108.htmlTechArticleRSS, also called Really Simple Syndication or RDF Site Summary, is a A file format that allows Web sites to publish and aggregate the latest content to users...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

See all articles