views:

89

answers:

1

Hey,

I have used this php to fetch my blog's latest post:

function read_rss($display=0,$url='') {
    $doc = new DOMDocument();
    $doc->load($url);
    $itemArr = array();

    foreach ($doc->getElementsByTagName('item') as $node) {
        if ($display == 0) {
            break;
        }

        $itemRSS = array (
            'title'       => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'description' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            'link'        => $node->getElementsByTagName('link')->item(0)->nodeValue,
        );

         array_push($itemArr, $itemRSS);

        $display--;
    }
    return $itemArr;
}

I learnt this off a tutorial as I wasn't sure how to do this task. However it works, but I keep getting this error printed in my error log:

[12-Jun-2010 06:13:36] PHP Warning:  DOMDocument::load() [<a href='domdocument.load'>domdocument.load</a>]: Document is empty in http://www.prettyklicks.com/blog/?feed=rss2, line: 1 in public_html/includes/functions.php on line 153
[12-Jun-2010 06:13:36] PHP Warning:  DOMDocument::load() [<a href='domdocument.load'>domdocument.load</a>]: Start tag expected, '&lt;' not found in http://www.prettyklicks.com/blog/?feed=rss2, line: 1 in public_html/includes/functions.php on line 153

Any ideas?

Thanks!

A: 

Hi Stefan,

I had the same problem and here's the solution:

Replace the line:

$doc->load($url);

with

$doc->loadXML(preg_replace("/>\s+<", file_get_contents($url)));

What this does is to load the url into a string, strip out all whitespace between tags and then pass it to the DOMDocument object for loading.

Why should whitespace matter? I'm not sure but it seems that the WordPress RSS feed contains whitespace to make it nicely indented, but this interferes with the DOMDocument's parser and makes it look like there's a missing tag.

Credit to http://netweblogic.com/php/domdocument-whitespace-php/ where I found the answer; they solve the same problem for a different situation.

Strangely (and I don't get this), my code works without the workaround on my development server but not on the production server. I'm not sure why but it must have something to do with version & config of Apache/PHP/WordPress.

Anyway, I hope this helps and it's not too late!

Paul.

Paul Masri
Your advice was spot on except your code needed a little adjusting. you were missing a parameter in the preg_replace and the delimiter in your pattern. But thank you that worked well!
Stefan