2009-02-17 2 views
2

Я использую Simple HTML DOM, чтобы очистить страницу за последние новости, а затем создать RSS-канал, используя этот PHP class.Очистить и сгенерировать RSS-канал

Это то, что я сейчас:

<?php 

// This is a minimum example of using the class 
include("FeedWriter.php"); 
include('simple_html_dom.php'); 

$html = file_get_html('http://www.website.com'); 

foreach($html->find('td[width="380"] p table') as $article) { 
$item['title'] = $article->find('span.title', 0)->innertext; 
$item['description'] = $article->find('.ingress', 0)->innertext; 
$item['link'] = $article->find('.lesMer', 0)->href;  
$item['pubDate'] = $article->find('span.presseDato', 0)->plaintext;  
$articles[] = $item; 
} 


//Creating an instance of FeedWriter class. 
$TestFeed = new FeedWriter(RSS2); 


//Use wrapper functions for common channel elements 

$TestFeed->setTitle('Testing & Checking the RSS writer class'); 
$TestFeed->setLink('http://www.ajaxray.com/projects/rss'); 
$TestFeed->setDescription('This is test of creating a RSS 2.0 feed Universal Feed Writer'); 

    //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0 

    $TestFeed->setImage('Testing the RSS writer class','http://www.ajaxray.com/projects/rss','http://www.rightbrainsolution.com/images/logo.gif'); 


foreach($articles as $row) { 

    //Create an empty FeedItem 
    $newItem = $TestFeed->createNewItem(); 

    //Add elements to the feed item  
    $newItem->setTitle($row['title']); 
    $newItem->setLink($row['link']); 
    $newItem->setDate($row['pubDate']); 
    $newItem->setDescription($row['description']); 

    //Now add the feed item 
    $TestFeed->addItem($newItem); 
} 

    //OK. Everything is done. Now genarate the feed. 
    $TestFeed->genarateFeed(); 

?> 

Как я могу сделать этот код проще? Правильно знаю, есть два заявления foreach, как я могу их объединить?

Поскольку новость соскользнула на норвежском языке, мне нужно применить html_entity_decode() для названия. Я пробовал, но я не мог заставить его работать:

foreach($html->find('td[width="380"] p table') as $article) { 
$item['title'] = html_entity_decode($article->find('span.title', 0)->innertext, ENT_NOQUOTES, 'UTF-8'); 
$item['description'] = "<img src='" . $article->find('img[width="100"]', 0)->src . "'><p>" . $article->find('.ingress', 0)->innertext . "</p>";  
$item['link'] = $article->find('.lesMer', 0)->href;  
$item['pubDate'] = unix2rssdate(strtotime($article->find('span.presseDato', 0)->plaintext)); 
$articles[] = $item; 
} 

Спасибо :)

ответ

3

Ну для всего простого сочетания двух петель можно создать фид, как ваш разбор через HTML-код:

<?php 
include("FeedWriter.php"); 
include('simple_html_dom.php'); 

$html = file_get_html('http://www.website.com'); 

//Creating an instance of FeedWriter class. 
$TestFeed = new FeedWriter(RSS2); 
$TestFeed->setTitle('Testing & Checking the RSS writer class'); 
$TestFeed->setLink('http://www.ajaxray.com/projects/rss'); 
$TestFeed->setDescription(
    'This is test of creating a RSS 2.0 feed Universal Feed Writer'); 

$TestFeed->setImage('Testing the RSS writer class', 
        'http://www.ajaxray.com/projects/rss', 
        'http://www.rightbrainsolution.com/images/logo.gif'); 

//parse through the HTML and build up the RSS feed as we go along 
foreach($html->find('td[width="380"] p table') as $article) { 
    //Create an empty FeedItem 
    $newItem = $TestFeed->createNewItem(); 

    //Look up and add elements to the feed item 
    $newItem->setTitle($article->find('span.title', 0)->innertext); 
    $newItem->setDescription($article->find('.ingress', 0)->innertext); 
    $newItem->setLink($article->find('.lesMer', 0)->href);  
    $newItem->setDate($article->find('span.presseDato', 0)->plaintext);  

    //Now add the feed item 
    $TestFeed->addItem($newItem); 
} 

$TestFeed->genarateFeed(); 
?> 

что вопрос, что вы видите с html_entity_decode, если вы даете нам ссылку на страницу, она не работает на том, что может помочь?

4

Кажется, что вы пробиваете $html, чтобы построить массив статей, а затем прокрутите их, добавив в фид - вы можете пропустить весь цикл здесь, добавив элементы в фид, как они найдены. Чтобы сделать это, вам нужно переместить FeedWriter, немного перестроить в потоке выполнения.

Я бы также добавил несколько методов, чтобы помочь с читабельностью, что может помочь в ремонтопригодности в долгосрочной перспективе. Инкапсулирование создания фида, модификация элемента и т. Д. Должны облегчить вам, если вам когда-либо понадобится подключить другой класс провайдера для фида, изменить правила синтаксического анализа и т. Д. Дальнейшие улучшения можно сделать по приведенному ниже коду (html_entity_decode находится на отдельная строка от $item['title'] и т. д.), но вы получите общую идею.

В чем проблема с html_entity_decode? У вас есть образец ввода/вывода?

<?php 

// This is a minimum example of using the class 
include("FeedWriter.php"); 
include('simple_html_dom.php'); 

// Create new instance of a feed 
$TestFeed = create_new_feed(); 

$html = file_get_html('http://www.website.com'); 

// Loop through html pulling feed items out 
foreach($html->find('td[width="380"] p table') as $article) 
{ 
    // Get a parsed item 
    $item = get_item_from_article($article); 

    // Get the item formatted for feed 
    $formatted_item = create_feed_item($TestFeed, $item); 

    //Now add the feed item 
    $TestFeed->addItem($formatted_item); 
} 

//OK. Everything is done. Now generate the feed. 
$TestFeed->generateFeed(); 


// HELPER FUNCTIONS 

/** 
* Create new feed - encapsulated in method here to allow 
* for change in feed class etc 
*/ 
function create_new_feed() 
{ 
    //Creating an instance of FeedWriter class. 
    $TestFeed = new FeedWriter(RSS2); 

    //Use wrapper functions for common channel elements 
    $TestFeed->setTitle('Testing & Checking the RSS writer class'); 
    $TestFeed->setLink('http://www.ajaxray.com/projects/rss'); 
    $TestFeed->setDescription('This is test of creating a RSS 2.0 feed Universal Feed Writer'); 

    //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0 
    $TestFeed->setImage('Testing the RSS writer class','http://www.ajaxray.com/projects/rss','http://www.rightbrainsolution.com/images/logo.gif'); 

    return $TestFeed; 
} 


/** 
* Take in html article segment, and convert to usable $item 
*/ 
function get_item_from_article($article) 
{ 
    $item['title'] = $article->find('span.title', 0)->innertext; 
    $item['title'] = html_entity_decode($item['title'], ENT_NOQUOTES, 'UTF-8'); 

    $item['description'] = $article->find('.ingress', 0)->innertext; 
    $item['link'] = $article->find('.lesMer', 0)->href;  
    $item['pubDate'] = $article->find('span.presseDato', 0)->plaintext;  

    return $item; 
} 


/** 
* Given an $item with feed data, create a 
* feed item 
*/ 
function create_feed_item($TestFeed, $item) 
{ 
    //Create an empty FeedItem 
    $newItem = $TestFeed->createNewItem(); 

    //Add elements to the feed item  
    $newItem->setTitle($item['title']); 
    $newItem->setLink($item['link']); 
    $newItem->setDate($item['pubDate']); 
    $newItem->setDescription($item['description']); 

    return $newItem; 
} 
?> 
0

Возможно, вы можете использовать что-то вроде Feedity - http://feedity.com, которое уже решает проблему сгенерировать RSS-канал с любой веб-страницы.

Смежные вопросы