Reputation: 1845
I am trying to get the title and link of an rss feed -
https://www.reddit.com/r/gif.rss
(the reddit feed)
xml=simplexml_load_file("https://www.reddit.com/r/gif.rss") or die("Error: Cannot create object");
foreach ($xml->entry->content as $x) {
$title = $x->title;
$string = $x->link;
echo $title;
echo "<br>";
echo $string;
}
I can't get title or link to appear.
Upvotes: 0
Views: 1004
Reputation: 1845
Sorted it out:
$xml=simplexml_load_file("https://www.reddit.com/r/gif.rss") or die("Error: Cannot create object");
function extractString($string, $start, $end) {
$string = " ".$string;
$ini = strpos($string, $start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
foreach ($xml->entry as $x) {
$string = $x->content;
$url = extractString($string, '<span><a href="', '">[link]</a></span>');
$title = extractString($string, 'alt="', '" title');
Upvotes: 2
Reputation: 107687
Simply adjust your path expression. The <content>
node does not contain <title>
or <link>
children though their content is contained in content's text value. Instead, the nodes you need are siblings, so remove <content>
in loop path:
$xml = simplexml_load_file("https://www.reddit.com/r/gif.rss")
or die("Error: Cannot create object");
foreach ($xml->entry as $x) {
$title = $x->title;
$string = $x->link['href'];
echo $title;
echo "<br>";
echo $string;
}
// This guy loves his job
// <br>
// https://www.reddit.com/r/gif/comments/53i3jc/this_guy_loves_his_job/
// Letron BMW E92 Transformer
// <br>
// https://www.reddit.com/r/gif/comments/53i13r/letron_bmw_e92_transformer/
// MRW "you're cute when you're angry"
// <br>
// https://www.reddit.com/r/gif/comments/53ihpf /mrw_youre_cute_when_youre_angry/
// Pussy Pass Denied
// <br>
// https://www.reddit.com/r/gif/comments/53hm3w/pussy_pass_denied/
// My favorite reverse gif so far
// <br>
// https://www.reddit.com/r/gif/comments/53ihwr/my_favorite_reverse_gif_so_far/
// Oh hooman, you will hug me. --Dog
// <br>
// https://www.reddit.com/r/gif/comments/53cbcq/oh_hooman_you_will_hug_me_dog/
...
Upvotes: 1