如何从可用的Feed数据中随机显示2个最新的Feed?

时间:2011-04-19 10:54:07

标签: php rss feed

我必须在一个页面的不同部分显示不同的Feed, 同样我有从Feed网址创建的数组,就像

Array
(
    [0] => Array
        (
            [title] => Mono, Lack of Sun Linked to MS 
            [description] => Having a history of mononucleosis and low levels of sun exposure appear to be risk factors for multiple sclerosis.
            [link] => http://www.webmd.com/multiple-sclerosis/news/20110418/mono-lack-sun-linked-multiple-sclerosis?src=RSS_PUBLIC
            [category] => 
            [date] => Mon, 18 Apr 2011 19:17:38 EST
            [image] => 

sun rising over field of flowers

        )

    [1] => Array
        (
            [title] => Study: ADHD Linked to Preterm Birth 
            [description] => Researchers have found that babies who are born prematurely have an increased risk of developing attention deficit hyperactivity disorder (ADHD) in their school years, even when they are compared with their full-term siblings.
            [link] => http://www.webmd.com/add-adhd/news/20110418/study-adhd-linked-preterm-birth?src=RSS_PUBLIC
            [category] => 
            [date] => Mon, 18 Apr 2011 19:01:08 EST
            [image] => 

close up of preemie holding adults finger

        )

    [2] => Array
        (
            [title] => DNR Orders May Affect Surgical Outcomes 
            [description] => People with do-not-resuscitate (DNR) orders may be more than twice as likely to die soon after surgery, regardless of the urgency of the procedure or health status before surgery.
            [link] => http://www.webmd.com/news/20110418/dnr-orders-may-affect-surgical-outcomes?src=RSS_PUBLIC
            [category] => 
            [date] => Mon, 18 Apr 2011 18:34:31 EST
            [image] => 

senior man in hospital gown

        )

    [3] => Array
        (
            [title] => Most Parents Confident About Vaccine Safety 
            [description] => Two new studies seek to better understand parents’ attitudes about vaccine safety and analyze potential barriers to routine childhood vaccination.
            [link] => http://children.webmd.com/vaccines/news/20110418/most-parents-confident-about-vaccine-safety?src=RSS_PUBLIC
            [category] => 
            [date] => Mon, 18 Apr 2011 18:03:32 EST
            [image] => 

mom holding son as he gets vaccine

        )

    [4] => Array
        (
            [title] => ADHD: Genetic Mutation May Be Key 
            [description] => A single-letter change seen in the DNA of kids with ADHD causes hyperactivity in mice. Mice with the altered DNA have more excitable brain cells, which calm down when they get stimulant ADHD drugs.
            [link] => http://www.webmd.com/add-adhd/news/20110418/adhd-genetic-mutation-may-be-key?src=RSS_PUBLIC
            [category] => 
            [date] => Mon, 18 Apr 2011 16:44:03 EST
            [image] => 

boy losing focus at school

        )

    [5] => Array
        (
            [title] => Teen Suicide Attempts Tied to Social Environment 
            [description] => A negative social environment may increase risk for suicide attempts by lesbian, gay, and bisexual (LGB) teenagers.
            [link] => http://children.webmd.com/news/20110418/teen-suicide-attempts-tied-social-environment?src=RSS_PUBLIC
            [category] => 
            [date] => Mon, 18 Apr 2011 16:43:09 EST
            [image] => 

depressed teen girl

        )
}

现在我想从上面的数组中选取4个最新的供稿并显示3个供稿。

我该怎么做?

我正在使用PHP ..,

获取数组的代码如下:

class Rss
{
    /* Private variables */
    private $parser;
    private $feed_url;
    private $item;
    private $tag;
    private $output;
    private $counter = 0;

    /* Private variables for RSS */
    private $title = false;
    private $description = false;
    private $link = false;
    private $category = false;
    private $pubDate = false;
    private $image = false;

    /* Setup constants */
    const XML = 'XML'; // for XML parser
    const SXML = 'SXML'; // for SimpleXML parser
    const TXT = 'TXT'; // for text parser using regular expressions

    // {{{ construct
    /**
     * Constructor
     */
    function __construct(  )
    {
    }
    // }}}

    // {{{ getFeed
    /**
     * Get RSS feed from given URL, parse it and return
     * as classic array. You can switch between XML,
     * SimpleXML and text (regex) method of reading.
     *
     * @access      public
     * @param       <string> $url Feed URL
     * @param       <constant> $method Reading method
     */
    public function getFeed($url, $method = self::SXML)
    {
        /* Set counter to zero */
        $this->counter = 0;

        /* Method switch */
        switch($method) {
            case 'TXT': // Rss::TXT
                try {
                    return $this->txtParser($url);
                }
                catch (Exception $e) {
                    throw $e;
                }
                break;
            case 'SXML': // Rss::SXML
                try {
                    return $this->sXmlParser($url);
                }
                catch (Exception $e) {
                    throw $e;
                }
                break;
            default:
            case 'XML': // Rss::XML
                try {
                    return $this->xmlParser($url);
                }
                catch (Exception $e) {
                    throw $e;
                }
                break;
        }
    }
    // }}}

    // {{{ sXmlParser
    /**
     * Parser for the SimpleXML way.
     *
     * @access      private
     * @param       <string> $url Feed URL
     * @return      <array> $feed Array of items
     */
    private function sXmlParser($url)
    {
        /* Call SimpleXML on file */
        $xml = simplexml_load_file($url);

        /* Iterate */
        foreach($xml->channel->item as $item)   {
            $this->output[$this->counter]['title'] = $item->title;
            $this->output[$this->counter]['description'] = $item->description;
            $this->output[$this->counter]['link'] = $item->link;
            $this->output[$this->counter]['category'] = isset($item->category) ? $item->category : false;
            $this->output[$this->counter]['date'] = $item->pubDate;
            $this->counter++;
        }

        /* Return data */
        return $this->output;
    }
    // }}}

    // {{{ xmlParser
    /**
     * Parser for the XML way.
     *
     * @access      private
     * @param       <string> $url Feed URL
     * @return      <array> $feed Array of items
     */
    private function xmlParser($url)
    {
        /* Create XML parser */
        $this->parser = xml_parser_create();

        /* Set options (skip white spaces) */
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);

        /* Put $url to internal storage */
        $this->feed_url = $url;

        /* Use parser within our object */
        xml_set_object($this->parser, $this);

        /* Set element handlers */
        xml_set_element_handler($this->parser, "xmlStartElement", "xmlEndElement");

        /* Set data handler */
        xml_set_character_data_handler($this->parser, "xmlCharacterData");

        /* Open feed */
        try {
            $this->xmlOpenFeed();
        }
        catch (Exception $e) {
            throw $e;
        }

        /* Return data */
        return $this->output;
    }
    // }}}

    // {{{ getFile
    /**
     * Retrieve file contents for usage in Rss::XML
     * and Rss::TXT
     *
     * @access      private
     * @param       <string> $url Feed URL
     * @return      <string> $feed File contents
     */
    private function getFile($url)
    {
        /* Initialize variables */
        $feed = false;

        /* Use cURL if possible */
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_USERAGENT, 'RSS Feed Reader v2.2 (http://www.phpclasses.org/package/3724-PHP-Parse-and-display-items-of-an-RSS-feed.html)');
            $feed = curl_exec($curl);
            curl_close($curl);
        }
        /* Otherwise, try to use file_get_contents() */
        else if (function_exists('file_get_contents')) {
            $feed = file_get_contents($url); // read
        }
        /* And as a last attempt, try to use fopen() */
        else {
            /* Try to open file */
            $fh = fopen($url, 'r');

            /* Iterate */
            while(!feof($fh))   {
                $feed .= fread($fh, 4096); // read
            } // while(!feof($fh))
        }

        /* If we get no results, throw an exception */
        if ($feed === false)
            throw new Exception("I'm sorry but there's simply no way how I can load the feed...");

        /* Return data */
        return $feed;
    }


    // {{{ txtParser
    /**
     * Shortcut for regex parsing with Rss::TXT
     *
     * @access      private
     * @param       <string> $url Feed URL
     * @return      <array> $feed Array of items
     */
    private function txtParser($url)
    {
        /* Retrieve feed content */
        try {
            $feed = $this->getFile($url);
        }
        catch (Exception $e) {
            throw $e;
        }

        /* Parse */
        $this->txtParseFeed($feed);

        /* Return data */
        return $this->output;
    }
    // }}}

    // {{{ xmlOpenFeed
    /**
     * Reads file for usage with Rss::XML
     *
     * @access      private
     * @return      <void>
     */
    private function xmlOpenFeed()
    {
        /* Retrieve feed content */
        try {
            $feed = $this->getFile($this->feed_url);
        }
        catch (Exception $e) {
            throw $e;
        }

        /* Parse */
        xml_parse($this->parser, $feed, true);

        /* Free parser */
        xml_parser_free($this->parser);
    }
    // }}}

    // {{{ xmlStartElement
    /**
     * Item start handler for Rss::XML parser
     *
     * @access      private
     * @param       <object> $parser Parser reference
     * @param       <string> $tag Tag
     * @return      <void>
     */
    private function xmlStartElement($parser, $tag)
    {
        if ($this->item === true)   {
            $this->tag = $tag;
        }
        else if ($tag === "ITEM")   {
            $this->item = true;
        }
    }
    // }}}

    // {{{ xmlCharacterElement
    /**
     * Item content handler for Rss::XML parser
     *
     * @access      private
     * @param       <object> $parser Parser reference
     * @param       <string> $data Content data
     * @return      <void>
     */
    private function xmlCharacterData($parser, $data)
    {
        /* Run only if we're inside an item */
        if ($this->item === TRUE)   {
            /* Read content tags */
            switch ($this->tag) {
                case "TITLE":
                    $this->title .= $data;
                    break;
                case "CATEGORY":
                    $this->category .= $data;
                    break;
                case "DESCRIPTION":
                    $this->description .= $data;
                    break;
                case "LINK":
                    $this->link .= $data;
                    break;
                case "PUBDATE":
                    $this->pubDate .= $data;
                    break;
                case "IMAGE":
                    $this->image .= $data;
                    break;
            }
        }
    }
    // }}}

    // {{{ xmlEndElement
    /**
     * Item end handler
     *
     * @access      private
     * @param       <object> $parser Parser reference
     * @param       <string> $tag Tag
     * @return      <void>
     */
    function xmlEndElement($parser, $tag)
    {
        if ($tag == 'ITEM') {
            $this->output[$this->counter]['title'] = trim($this->title);
            $this->output[$this->counter]['description'] = trim($this->description);
            $this->output[$this->counter]['category'] = isset($this->category) ? trim($this->category) : false;
            $this->output[$this->counter]['link'] = trim($this->link);
            $this->output[$this->counter]['date'] = trim($this->pubDate);
            $this->output[$this->counter]['image'] = trim($this->image);
            $this->counter++;
            $this->title = false;
            $this->description = false;
            $this->category = false;
            $this->link = false;
            $this->pubDate = false;
            $this->image = false;
            $this->item = false;
        }
    }
    // }}}

    // {{{ txtParseFeed
    /**
     * Parse feed using regexp
     *
     * @access      private
     * @param       <string> $feed Feed string
     * @return      <void>
     */
    private function txtParseFeed($feed)
    {
        $feed = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $feed);
        $feed = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $feed);
        preg_match_all('|<item>(.*)</item>|U', $feed, $m);
        foreach($m[1] as $item) {
            preg_match('|<title>(.*)</title>|U', $item, $title);
            preg_match('|<link>(.*)</link>|U', $item, $link);
            preg_match('|<category>(.*)</category>|U', $item, $category);
            preg_match('|<description>(.*)</description>|U', $item, $description);
            preg_match('|<pubDate>(.*)</pubDate>|U', $item, $pubdate);
            preg_match('|<media:text type="html">(.*)</media:text>|U', $item, $image);
            $this->output[$this->counter]['title'] = $title[1];
            $this->output[$this->counter]['description'] = $description[1];
            $this->output[$this->counter]['link'] = $link[1];
            $this->output[$this->counter]['category'] = isset($category[1]) ? $category[1] : false;
            $this->output[$this->counter]['date'] = $pubdate[1];
            $this->output[$this->counter]['image'] = $image[1];
            $this->counter++;
        }
    }
    // }}}

    // {{{ destruct
    /**
     * Destructor
     */
    function __destruct()
    {
    }
    // }}}

}

$Rss = new Rss;

/*
    Text way
*/
try {
    $feed = $Rss->getFeed('http://rssfeeds.webmd.com/rss/rss.aspx?RSSSource=RSS_PUBLIC', Rss::TXT);
    echo '<pre>';
    echo '<pre>';print_r($feed);exit;
    foreach($feed as $item) {
        echo "<b>Title:</b> <a href=\"$item[link]\">$item[title]</a>\n";
        echo "<b>Published:</b> $item[date]\n";
        echo "<b>Category:</b> $item[category]\n";
        echo "\n$item[image]\n";
        echo "\n$item[description]\n";
        echo "<hr/>";
    }
    echo '</pre>';
}
catch (Exception $e) {
    echo $e->getMessage();
}

请帮助我获得我需要的结果......

3 个答案:

答案 0 :(得分:1)

您可以使用shuffle()

$numbers = range(0, sizeof($feed_array));
srand((float)microtime() * 1000000);
shuffle($numbers);
for($i=0, $i<2; $i++){
    echo $feed_array($numbers[$i]);
}

答案 1 :(得分:1)

我认为RSS源仍然是按日期顺序排列的,因此最新的RSS源是第一个。如果是这样,那么为了获得4个馈送中的随机3个,您可以执行以下操作。

$feeds = //the array
shuffle($feeds);
$first = $feeds[0];
$second = $feeds[1];
$third = $feeds[2];

答案 2 :(得分:1)

或者你也可以使用 - array_rand($ feed_array,2);

srand((float) microtime() * 10000000);

$rand_keys = array_rand($feed_array, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
相关问题