我正在尝试使用以下代码从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对象的值?我只想要价值而不是对象。有人可以指出我做错了吗?
答案 0 :(得分:3)
SimpleXML在其对象上实现__toString()
magic method,否则由对象引用分配。当它们在echo
ed字符串的上下文中使用时(作为一个示例),您将获得返回的字符串值,但在正常的赋值或引用上,您将获得整个SimpleXMLElement
对象。
如果您想要字符串值,可以将其强制转换为字符串:
$feedDetails = array(
"feedName" => (string)$feedItem->FeedName,
"feedURL" => (string)$feedItem->FeedURL
);