0

I am using PHP to grab an XML feed and display it in my website, the feed is coming from This NewsReach Blog.

I am using some simple PHP code to get the details as show below:

    $feed = new SimpleXMLElement('http://blog.newsreach.co.uk/atom.xml', null, true);

    $i = 0;

    foreach($feed->entry as $entry)
    {
        if ($i < 4)
        {
            $title = mysql_real_escape_string("{$entry->title}");
            $summary = mysql_real_escape_string("{$entry->content}");
            $summary = strip_tags($summary);
            $summary = preg_replace('/\s+?(\S+)?$/', '', substr($summary, 0, 100));
            $url = mysql_real_escape_string("{$entry->link[4]['href']}");
            $media = $entry->children('http://search.yahoo.com/mrss/');
            $attrs = $media->thumbnail[0]->attributes();
            $img = $attrs['url'];
        }
    }

The problem that I have is that the media thumbnail tag does not exist in every blog post which causes an error to appear and stop the XML Grabber from functioning.

I have tired things like:

    if ($media == 0)
    {
    }
    else
    {
        $attrs = $media->thumbnail[0]->attributes();
            $img = $attrs['url'];
    }

or

    if ($media['thumbnail'] == 0)
    {
    }
    else
    {
        $attrs = $media->thumbnail[0]->attributes();
            $img = $attrs['url'];
    }

which I had no luck with, I was hoping someone could help me check if the XML Item existed and then process depending on that.

Thanks all

1
  • Check if the element exists with isset($media->thumbnail[0]) Commented Sep 22, 2011 at 8:56

1 Answer 1

1

You could check if it's set and not empty:

$img = '';
if (!empty($media->thumbnail[0])) {
    $attrs = $media->thumbnail[0]->attributes();
    $img = $attrs['url'];
}

Remember that $media is an object, you can't access it like an array ($media['thumbnail'] should be $media->thumbnail).

Sign up to request clarification or add additional context in comments.

1 Comment

Thats where I was getting confused, I was getting mixed up with thinking $media was an array not an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.