格式化simplexml对象是错误的

时间:2013-12-21 22:23:10

标签: php xml

我正在尝试从simpleXML对象进行格式化,但它返回:

title1title2title3<a href=""></a>

即使这是......

 return '<a href="'.$url.'">'.$title.'</a>';

这是我的整个代码。

<?php 

class ForumFeed {
    private function getXMLFeeds($feed = 'all')
    {
        /*
            Fetch the XML feeds
         */
        $globalFeedXML = file_get_contents('/forum/syndication.php?limit=3');
        $newsFeedXML = file_get_contents('/forum/syndication.php?fid=4&limit=3');

        /*
            Turn feed objects
         */
        $globalFeed = new SimpleXMLElement($globalFeedXML);
        $newsFeed = new SimpleXMLElement($newsFeedXML);

        /*
            Return requested feed
         */
        if ($feed == 'news') {
            return $newsFeed;
        } else if ($feed == 'all') {
            return $globalFeed;
        } else {
            return false;
        }

    }
    private function formatFeeds($feed, $node)
    {
        /*
            Format Feeds for displayable content..
         */
        $getFeedObject = $this->getXMLFeeds($feed);
        $feedData = $getFeedObject->xpath('channel/item/'.$node);
        while (list( , $node) = each($feedData)) {
            echo $node;
        }
    }

    public function feed($feed)
    {
        $title = $this->formatFeeds($feed, 'title');
        $url = $this->formatFeeds($feed, 'url');
        return '<a href="'.$url.'">'.$title.'</a>';
    }
}

$feeds = new ForumFeed();

echo $feeds->feed('all');

我不确定我做错了什么。

1 个答案:

答案 0 :(得分:0)

问题在于这个功能:

private function formatFeeds($feed, $node)
{
    /*
        Format Feeds for displayable content..
     */
    $getFeedObject = $this->getXMLFeeds($feed);
    $feedData = $getFeedObject->xpath('channel/item/'.$node);
    while (list( , $node) = each($feedData)) {
        echo $node;
    }
}

它回显$node,而不是向调用者返回任何内容。尝试这样的事情:

private function formatFeeds($feed, $node)
{
    /*
        Format Feeds for displayable content..
     */
    $getFeedObject = $this->getXMLFeeds($feed);
    $feedData = $getFeedObject->xpath('channel/item/'.$node);
    $result = array();
    while (list( , $node) = each($feedData)) {
        $result[] = $node;
    }
    return implode(', ', $result);
}