简体   繁体   中英

PHP - Echo key value of the array items

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" 
} 

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>';

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);

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();
}

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM