2

我正在尝试使用以下代码从 XML 文件中读取一些 RSS 提要详细信息:

$this->feedFile = file_get_contents(__ROOT__ . '/assets/feedList.xml'); //Define this externally
$this->feedDetailsArray = array();
$this->feedXML = new SimpleXMLElement($this->feedFile);
echo "1. =========";
print_r($this->feedXML);
echo "1. =========";
foreach($this->feedXML->Feed as $feedItem) {
    echo "2. =========";
    echo "AJ:: feedName " . var_dump($feedItem->FeedName) . " feedURL " . var_dump($feedItem->FeedURL) . "\n";
    echo "2. =========";
    $feedDetails = array(
        "feedName" => $feedItem->FeedName,
        "feedURL" => $feedItem->FeedURL/*,
        'favIconURL' => $feedItem->FavIconURL
        );
    echo "3. =========";
    var_dump($feedDetails);
    echo "3. =========";

print_r 输出以下内容:

1. =========SimpleXMLElement Object
(
    [Feed] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [FeedName] => Hacker News
                    [FeedURL] => http://news.ycombinator.com/rss
                    [FavIconURL] => http://ycombinator.com/favicon.ico
                    [Segment] => Startups
                )

    .
    .
    .

第一个 var_dump ( echo "feedName " . var_dump($feedItem->FeedName) . " feedURL " . var_dump($feedItem->FeedURL) . "\n";) 输出:

2. =========class SimpleXMLElement#38 (1) {
    string(11) "Hacker News"
}
class SimpleXMLElement#38 (1) {
    string(31) "http://news.ycombinator.com/rss"
}
AJ:: feedName  feedURL 
2. =========

第二个 var_dump 输出:

3. =========array(2) {
  'feedName' =>
  class SimpleXMLElement#38 (1) {
        string(11) "Hacker News"
  }
  'feedURL' =>
  class SimpleXMLElement#37 (1) {
        string(31) "http://news.ycombinator.com/rss"
  }
}
3. =========

我的问题是,为什么该语句"feedName" => $feedItem->FeedName导致分配对象而不是 SimpleXML 对象的值?我只想要价值而不是对象。有人可以指出我做错了什么吗?

4

1 回答 1

3

SimpleXML 在其对象上实现了__toString()魔术方法,这些对象是由对象引用指定的。当它们在echoed 字符串的上下文中使用时(作为一个示例),您将获得返回的字符串值,但在正常的赋值或引用中,您将获得整个SimpleXMLElement对象。

如果需要字符串值,可以将其转换为字符串:

$feedDetails = array(
    "feedName" => (string)$feedItem->FeedName,
    "feedURL" => (string)$feedItem->FeedURL
 );
于 2012-10-19T12:52:05.093 回答