Created
May 7, 2013 09:57
-
-
Save enricodeleo/5531546 to your computer and use it in GitHub Desktop.
read an atom feed as XML in php 5+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Lettore Feed Atom come xml | |
// Requisito minimo php5 | |
// Funzione che limita il numero di caratteri di una stringa | |
function strlimit($string, $limit) { | |
if (strlen($string) > $limit) { | |
$string = substr($string, 0, strrpos(substr($string, 0, $limit), ' ')) . '...'; | |
} | |
return $string; | |
} | |
// Funzione che cerca la prima immagine di un articolo. Se non la trova ne restituisce una predefinita | |
function get_first_image($analisi) { | |
$first_img = ''; | |
ob_start(); | |
ob_end_clean(); | |
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $analisi, $matches); | |
$first_img = $matches [1] [0]; | |
if(empty($first_img)){ | |
//Definisco l'immagine predefinita | |
$first_img = '/images/default.png'; | |
// l'immagine predefinita si trova nella cartella "images" | |
} | |
return $first_img; | |
} | |
//leggo il feed, il file xml risultante sarà un oggetto | |
$feed = simplexml_load_file('http://www.chacka.altervista.org/forum/feed.php'); | |
//imposto un contatore per limitare i risultati da stampare | |
$count = 0; | |
$maxposts = 3; //<--- da modificare | |
//itero nel mio oggetto feed con un ciclo | |
foreach($feed->entry as $article) { | |
//variabili che userò per ogni articolo da mostrare | |
$title = $article->title; | |
$category = $article->category; | |
$content = $article->content; | |
$link = $article->link[0]['href']; | |
$author = $article->author->name; | |
$published = $article->published; | |
?> | |
<!-- HTML DA PERSONALIZZARE --> | |
<div class="post"> | |
<h2><a href="<?php echo $link; ?>"><?php echo $title; ?></a></h2> | |
<img src="<?php echo get_first_image($content); ?>" /> | |
<p> | |
<!-- devo cambiare il secondo parametro con il numero di caratteri da mostrare --> | |
<?php echo strip_tags(strlimit( $content , 350 ),'<strong><b><i><em><u>');?> | |
</p> | |
<div class="meta-info"> | |
<span>di <strong><?php echo $author; ?></strong>, pubblicato nella categoria <strong><?php echo $category; ?></strong> pubblicato il <strong><?php echo $published; ?></strong></span> | |
</div> | |
</div> | |
<?php | |
$count++; //incremento il contatore | |
if( $count == $maxposts ) break; | |
} | |
//chiudo il foreach | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment