I'm currently using SimplePie to parse RSS news feeds. I am successfully merging the feeds using an array, however what I need to do is return single words at random from the title, not just the whole title. Can this be done in PHP at all? I was toying around with explode()
; however didn't have any luck.
Do I need to introduce some Javascript of some sort, after the data is parsed? I know this is a little vague, I'm just trying to get a sense of what is possible (I am open to using an alternative to SimplePie, this is just what I have used so far).
Here is my code right now, which simply returns the titles as whole:
<?php
//link simplepie
require_once ('simplepie/autoloader.php');
//new simplepie class
$feed = new SimplePie();
$feed->enable_cache(true);
$feed->set_cache_duration(60);
//set up feeds
$feed->set_feed_url(array('http://mf.feeds.reuters.com/reuters/UKTopNews' , 'http://www.theguardian.com/world/rss'
));
//run simplepie
$feed->init();
//handle content type
$feed->handle_content_type();
?>
<!DOCTYPE html>
<head>
<title>News</title>
<link rel="stylesheet" type="text/css" href='style.css'>
</head>
<body>
<div class = "headlines">
<?php foreach ($feed->get_items(0, 10) as $item): ?>
<?php $item->get_title(); ?>
<h4><?php echo $item->get_title(); ?></h4>
<?php endforeach; ?>
</div>
</body>
</html>
Thanks!
I need to do is return single words at random from the title
I hope i got your question right, "return a random word from title", right? Your problem is unrelated to SimplePie. Whenever you have a problem, try to reduce it to the minimum problem: here it's only a "how to work with strings" problem.
For your use-case:
$title = $item->get_title();
echo array_rand(array_flip(explode(' ', $title)), 1);
Standalone example:
$string = 'This is an example headline and it contains a lot of words.';
echo array_rand(array_flip(explode(' ', $string)), 1);
How does this work:
First the title string is exploded at the space char. You get an array back. It's key=>value, where value is a word from the string. Now, we flip values and keys - to get the values as keys and then we random pick 1 element by using array_rand().
This might needs some additional tweaking to cut commas and fullstops away and get it working with special chars. But it should get you started.