php - simplexml 'Trying to get property of non-object in' error

133

I'm trying to parse the XML of http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175 but I get this error, can't find whats wrong.

Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 9

<?php  
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175'); 

for($i=0;$i<10;$i+=1) {
    $namespaces = $rss->getNameSpaces(true);
    $dc = $rss->children($namespaces['dc']);

    echo "Title: " . $rss->channel->item[$i]->title . "<br>";
    echo "Creator: " . $dc->channel->item[$i]->creator . "<br>";
    echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
}  

And my second question.

Why is this code only working properly athttp://www.mpgh.net/forum/external.php?type=RSS2&forumids=175 and not at other pages likehttp://www.mpgh.net/forum/external.php?type=RSS2&forumids=168

Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 7

<?php
$rss = New DOMDocument();
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168'); 

for($i=0;$i<10;$i+=1) {

    if (substr($rss->channel->item[$i]->title, 0, 9) == '[Release]') {
        echo "Title: " . $rss->channel->item[$i]->title . "<br>";
        echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
    } else {
        echo 'Hoi<br><br>';
    }
}

Thanks.

275

Answer

Solution:

I think the problem is that$ith index of$rss->channel->item is not set or not an object.

Try this; it will expose the problem:

$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175'); 

if ($rss===null || !is_object($rss))
    die('Failed to load xml file.');
if (!is_object($rss->channel))
    die('Channel is not an object!');

foreach ($rss->channel->item as $item)
    if (is_object($item)) {
        $namespaces = $rss->getNameSpaces(true);
        $dc = $rss->children($namespaces['dc']);

        echo "Title: " . $item->title . "<br>";
        echo "Creator: " . $item->creator . "<br>";
        echo "Link: " . $item->link . "<br><br>";
    }

People are also looking for solutions to the problem: How to use a variable in 2 different Php files?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.