开发者

php error when XML item does not exist

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_stri开发者_如何学Gong("{$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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜