I’m trying to read a few RSS feed details from a XML file with the following code:
$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. =========";
The print_r outputs the following:
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
)
.
.
.
The first var_dump (echo "feedName " . var_dump($feedItem->FeedName) . " feedURL " . var_dump($feedItem->FeedURL) . "\n";) outputs:
2. =========class SimpleXMLElement#38 (1) {
string(11) "Hacker News"
}
class SimpleXMLElement#38 (1) {
string(31) "http://news.ycombinator.com/rss"
}
AJ:: feedName feedURL
2. =========
And the 2nd var_dump outputs:
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. =========
My question is, why does the statement "feedName" => $feedItem->FeedName result in the object being assigned instead of the value of the SimpleXML object? I only want the value and not the object. Can someone please point out what I’m doing wrong?
SimpleXML implements the
__toString()magic method on its objects, which are otherwise assigned by object reference. When they are used in context of anechoed string (as one example), you’ll get the string value returned, but on a normal assignment or reference you’ll get the wholeSimpleXMLElementobject.If you want the string value, you can cast it to a string: