Reputation: 13843
I need to echo the key value of an array.
This is how im outputting my array:
foreach($xml->channel->item as $item) {
$item->title
}
I've tried adding:
foreach($xml->channel->item as $key => $item)
But the value I echo just comes out as: item
Any ideas?
Var Dump of item results:
var_dump($xml->channel->item);
object(SimpleXMLElement)#4 (5) {
["title"]=> string(33) "BA and union agree to end dispute"
["description"]=> string(118) "British Airways and the Unite union reach an agreement which could end the long-running dispute between the two sides."
["link"]=> string(61) "http://www.bbc.co.uk/go/rss/int/news/-/news/business-13373638"
["guid"]=> string(43) "http://www.bbc.co.uk/news/business-13373638"
["pubDate"]=> string(29) "Thu, 12 May 2011 12:33:38 GMT"
}
Upvotes: 1
Views: 1330
Reputation: 2659
Hi maybe you could try to convert XML
the into Array
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
and then access it with foreach.
EXAMPLE
$x = new SimpleXMLElement(<<<EOXML
<root>
<node>Some Text</node>
</root>
EOXML
);
xml2array($x,&$out);
var_dump($out);
OUTPUT
array(1) {
["node"]=>
string(9) "Some Text"
}
Upvotes: 0
Reputation: 2407
foreach($xml->channel->item as $key => $item)
echo $key;
}
ADDED:
Check the answer here for converting it to array Trouble traversing XML Object in foreach($object as $key => $value);
Upvotes: 0
Reputation: 11385
It is not an array but a SimpleXMLElement. So loop through the children nodes and output the name.
foreach ( $xml->channel->item->children() as $child ) {
echo $child->getName();
}
Upvotes: 0
Reputation: 154543
Try doing:
$data = $xml->channel->item;
if (is_object($data) === true)
{
$data = get_object_vars($data);
}
echo '<pre>';
print_r(array_keys($data));
echo '</pre>';
Upvotes: 1