PHP - 数组项的Echo键值

时间:2011-05-12 22:58:11

标签: php

我需要回显一个数组的键值。

这就是输出我的数组的方式:

foreach($xml->channel->item as $item) {
  $item->title
}

我尝试添加:

foreach($xml->channel->item as $key => $item)

但我回应的价值只是:item

有什么想法吗?

项目结果的Var Dump:

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

4 个答案:

答案 0 :(得分:1)

尝试做:

$data = $xml->channel->item;

if (is_object($data) === true)
{
    $data = get_object_vars($data);
}

echo '<pre>';
print_r(array_keys($data));
echo '</pre>';

答案 1 :(得分:0)

    foreach($ xml-&gt; channel-&gt; item as $ key =&gt; $ item)         echo $ key;     }

增加:

检查此处的答案,将其转换为数组Trouble traversing XML Object in foreach($object as $key => $value);

答案 2 :(得分:0)

它不是数组而是SimpleXMLElement。因此,遍历子节点并输出名称。

foreach ( $xml->channel->item->children() as $child ) {
  echo $child->getName();
}

答案 3 :(得分:0)

您好,也许您可​​以尝试将XML转换为Array

function xml2array ( $xmlObject, $out = array () )
{
        foreach ( (array) $xmlObject as $index => $node )
            $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

        return $out;
}

然后使用foreach访问它。

示例

$x = new SimpleXMLElement(<<<EOXML
<root>
   <node>Some Text</node>
</root>
EOXML
);

xml2array($x,&$out);
var_dump($out);

<强>输出

array(1) {
  ["node"]=>
  string(9) "Some Text"
}