2011-05-12 93 views
1

我需要回顯數組的鍵值。PHP - 數組項的回顯鍵值

這是怎麼IM輸出我的數組:

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

我試着加入:

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

但我回顯值剛剛出來的:item

任何想法?項結果

瓦爾轉儲:

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

有你把'echo'在'$用品 - > title'的面前?嘗試'var_dump($ xml-> channel-> item'並調試它是否已經是'array'或不是。 – 2011-05-12 22:59:19

+0

我認爲這是一個SimpleXML對象,不一定會作爲數組轉儲出來 – 2011-05-12 23:00:57

回答

1

嘗試這樣做:

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

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

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

這給了我在項目下的每個條目的鍵: – CLiown 2011-05-12 23:15:41

+0

@CLiown:And你不需要這樣嗎?'foreach(array_keys($ data)as $ key){echo $ key;}'。 – 2011-05-13 01:20:21

0

的foreach($ XML->通道 - >項作爲$密鑰=> $項目) 回聲$密鑰; }

新增:

入住這裏將其轉換爲陣列Trouble traversing XML Object in foreach($object as $key => $value);

+0

echo result = item – CLiown 2011-05-12 23:03:56

+0

@CLiown是因爲它不是一個真正的數組,它是一個SimpleXMLElement,它模仿的是一個沒有真正索引的數組,只有很多值。 – 2011-05-12 23:06:43

+0

檢查加法。 – morgar 2011-05-12 23:10:26

0

答案這不是一個數組而是一個SimpleXMLElement。所以循環通過子節點並輸出名稱。

foreach ($xml->channel->item->children() as $child) { 
    echo $child->getName(); 
} 
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" 
} 
+0

我該如何使用它? – CLiown 2011-05-12 23:38:15

+0

這只是簡單的遞歸方法, xml2array($ xml,$ out)'然後'foreach($ out as $ key => $ value){} – Igor 2011-05-12 23:40:39

+0

結果爲NULL當我var_dump($ out) – CLiown 2011-05-12 23:57:43