TigerZF
🌐Español

33.2. Importación de feeds

Zend_Feed permite a los desarrolladores recuperar feeds muy fácilmente. Si conoce el URI de un feed, simplemente use el método Zend_Feed::import():

$feed = Zend_Feed::import('http://feeds.example.com/feedName');

También puede usar Zend_Feed para obtener el contenido de un feed desde un archivo o el contenido de una variable de cadena PHP:

// importing a feed from a text file
$feedFromFile = Zend_Feed::importFile('feed.xml');

// importing a feed from a PHP string variable
$feedFromPHP = Zend_Feed::importString($feedString);

En cada uno de los ejemplos anteriores, se devuelve un objeto de una clase que extiende Zend_Feed_Abstract en caso de éxito, dependiendo del tipo de feed. Si se recuperara un feed RSS mediante uno de los métodos de importación anteriores, entonces se devolvería un objeto Zend_Feed_Rss. Por otro lado, si se importara un feed Atom, entonces se devuelve un objeto Zend_Feed_Atom. Los métodos de importación también lanzarán un objeto Zend_Feed_Exception en caso de fallo, como un feed ilegible o mal formado.

33.2.1. Feeds personalizados

Zend_Feed permite a los desarrolladores crear feeds personalizados muy fácilmente. Solo tiene que crear un array e importarlo con Zend_Feed. Este array se puede importar con Zend_Feed::importArray() o con Zend_Feed::importBuilder(). En este último caso el array se calculará al vuelo mediante una fuente de datos personalizada que implemente Zend_Feed_Builder_Interface.

33.2.1.1. Importación de un array personalizado

// importing a feed from an array
$atomFeedFromArray = Zend_Feed::importArray($array);

// the following line is equivalent to the above;
// by default a Zend_Feed_Atom instance is returned
$atomFeedFromArray = Zend_Feed::importArray($array, 'atom');

// importing a rss feed from an array
$rssFeedFromArray = Zend_Feed::importArray($array, 'rss');

El formato del array debe ajustarse a esta estructura:

array(
    //required
    'title' => 'title of the feed',
    'link'  => 'canonical url to the feed',

    // optional
    'lastUpdate' => 'timestamp of the update date',
    'published'  => 'timestamp of the publication date',

    // required
    'charset' => 'charset of the textual data',

    // optional
    'description' => 'short description of the feed',
    'author'      => 'author/publisher of the feed',
    'email'       => 'email of the author',

    // optional, ignored if atom is used
    'webmaster' => 'email address for person responsible '
                .  'for technical issues',

    // optional
    'copyright' => 'copyright notice',
    'image'     => 'url to image',
    'generator' => 'generator',
    'language'  => 'language the feed is written in',

    // optional, ignored if atom is used
    'ttl'    => 'how long in minutes a feed can be cached '
             .  'before refreshing',
    'rating' => 'The PICS rating for the channel.',

    // optional, ignored if atom is used
    // a cloud to be notified of updates
    'cloud'       => array(
        // required
        'domain' => 'domain of the cloud, e.g. rpc.sys.com',

        // optional, defaults to 80
        'port' => 'port to connect to',

        // required
        'path'              => 'path of the cloud, e.g. /RPC2',
        'registerProcedure' => 'procedure to call, e.g. myCloud.rssPlsNotify',
        'protocol'          => 'protocol to use, e.g. soap or xml-rpc'
    ),

    // optional, ignored if atom is used
    // a text input box that can be displayed with the feed
    'textInput'   => array(
        // required
        'title'       => 'label of the Submit button in the text input area',
        'description' => 'explains the text input area',
        'name'        => 'the name of the text object in the text input area',
        'link'        => 'URL of the CGI script processing text input requests'
    ),

    // optional, ignored if atom is used
    // Hint telling aggregators which hours they can skip
    'skipHours' => array(
        // up to 24 rows whose value is a number between 0 and 23
        // e.g 13 (1pm)
        'hour in 24 format'
    ),

    // optional, ignored if atom is used
    // Hint telling aggregators which days they can skip
    'skipDays ' => array(
        // up to 7 rows whose value is
        // Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday
        // e.g Monday
        'a day to skip'
    ),

    // optional, ignored if atom is used
    // Itunes extension data
    'itunes' => array(
        // optional, default to the main author value
        'author' => 'Artist column',

        // optional, default to the main author value
        // Owner of the podcast
        'owner' => array(
            'name'  => 'name of the owner',
            'email' => 'email of the owner'
        ),

        // optional, default to the main image value
        'image' => 'album/podcast art',

        // optional, default to the main description value
        'subtitle' => 'short description',
        'summary'  => 'longer description',

        // optional
        'block' => 'Prevent an episode from appearing (yes|no)',

        // required, Category column and in iTunes Music Store Browse
        'category' => array(
            // up to 3 rows
            array(
                // required
                'main' => 'main category',

                // optional
                'sub'  => 'sub category'
            )
        ),

        // optional
        'explicit'     => 'parental advisory graphic (yes|no|clean)',
        'keywords'     => 'a comma separated list of 12 keywords maximum',
        'new-feed-url' => 'used to inform iTunes of new feed URL location'
    ),

    'entries' => array(
        array(
            //required
            'title' => 'title of the feed entry',
            'link'  => 'url to a feed entry',

            // required, only text, no html
            'description' => 'short version of a feed entry',

            // optional
            'guid' => 'id of the article, '
                   .  'if not given link value will used',

            // optional, can contain html
            'content' => 'long version',

            // optional
            'lastUpdate' => 'timestamp of the publication date',
            'comments'   => 'comments page of the feed entry',
            'commentRss' => 'the feed url of the associated comments',

            // optional, original source of the feed entry
            'source' => array(
                // required
                'title' => 'title of the original source',
                'url'   => 'url of the original source'
            ),

            // optional, list of the attached categories
            'category' => array(
                array(
                    // required
                    'term' => 'first category label',

                    // optional
                    'scheme' => 'url that identifies a categorization scheme'
                ),

                array(
                    // data for the second category and so on
                )
            ),

            // optional, list of the enclosures of the feed entry
            'enclosure'    => array(
                array(
                    // required
                    'url' => 'url of the linked enclosure',

                    // optional
                    'type' => 'mime type of the enclosure',
                    'length' => 'length of the linked content in octets'
                ),

                array(
                    //data for the second enclosure and so on
                )
            )
        ),

        array(
            //data for the second entry and so on
        )
    )
);

Referencias:

33.2.1.2. Importación de una fuente de datos personalizada

Puede crear una instancia de Zeed_Feed a partir de cualquier fuente de datos que implemente Zend_Feed_Builder_Interface. Solo tiene que implementar los métodos getHeader() y getEntries() para poder usar su objeto con Zend_Feed::importBuilder(). Como implementación de referencia sencilla, puede usar Zend_Feed_Builder, que toma un array en su constructor, realiza una validación menor, y luego puede usarse en el método importBuilder(). El método getHeader() debe devolver una instancia de Zend_Feed_Builder_Header, y getEntries() debe devolver un array de instancias de Zend_Feed_Builder_Entry.

[Note] Nota

Zend_Feed_Builder sirve como una implementación concreta para demostrar el uso. Se anima a los usuarios a crear sus propias clases para implementar Zend_Feed_Builder_Interface.

A continuación se muestra un ejemplo de uso de Zend_Feed::importBuilder():

// importing a feed from a custom builder source
$atomFeedFromArray =
    Zend_Feed::importBuilder(new Zend_Feed_Builder($array));

// the following line is equivalent to the above;
// by default a Zend_Feed_Atom instance is returned
$atomFeedFromArray =
    Zend_Feed::importBuilder(new Zend_Feed_Builder($array), 'atom');

// importing a rss feed from a custom builder array
$rssFeedFromArray =
    Zend_Feed::importBuilder(new Zend_Feed_Builder($array), 'rss');

33.2.1.3. Volcado del contenido de un feed

Para volcar el contenido de una instancia de Zend_Feed_Abstract, puede usar los métodos send() o saveXml().

assert($feed instanceof Zend_Feed_Abstract);

// dump the feed to standard output
print $feed->saveXML();

// send http headers and dump the feed
$feed->send();