访问XML文件中节点的索引号

时间:2013-02-04 15:53:39

标签: php xml simplexml

对于

等结构
SimpleXMLElement Object
(
    [id] => https://itunes.apple.com/us/rss/topfreeapplications/limit=2/genre=6014/xml
    [title] => iTunes Store: Top Free Applications in Games
    [updated] => 2013-02-04T07:18:54-07:00    
    [icon] => http://itunes.apple.com/favicon.ico
    [entry] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [updated] => 2013-02-04T07:18:54-07:00
                    [id] => https://itunes.apple.com/us/app/whats-word-new-quiz-pics-words/id573511269?mt=8&uo=2
                    [title] => What is the Word? - new quiz with pics and words - RedSpell
                )

            [1] => SimpleXMLElement Object
                (
                    [updated] => 2013-02-04T07:18:54-07:00
                    [id] => https://itunes.apple.com/us/app/temple-run-2/id572395608?mt=8&uo=2
                    [title] => Temple Run 2 - Imangi Studios, LLC
                )
        )

)

我正在使用以下代码定位entry节点,因为每个entry节点都代表游戏。

$xml = simplexml_load_file('the path to file');
foreach ($xml->entry as $val)
{                   
   $gameTitle = $val->title;    
   $gameLink = $val->id;
}

我正在寻找什么

定位entry节点的索引,即012等等;即。

[0] => SimpleXMLElement Object // <-- this fella here, capture 0
(
     [updated] => 2013-02-04T07:18:54-07:00
     [id] => https://itunes.apple.com/us/app/whats-word-new-quiz-pics-words/id573511269?mt=8&uo=2
     [title] => What is the Word? - new quiz with pics and words - RedSpell                  
)
[1] => SimpleXMLElement Object // <-- this fella here, capture 1
(
     [updated] => 2013-02-04T07:18:54-07:00
     [id] => https://itunes.apple.com/us/app/temple-run-2/id572395608?mt=8&uo=2
     [title] => Temple Run 2 - Imangi Studios, LLC
)

无论我做什么,我似乎都无法获得当前节点的索引。

更新

只是为了让人们测试Code Viper

1 个答案:

答案 0 :(得分:1)

您正在寻找名为iteator_to_array的功能,将第二个参数设置为false

$entries = iterator_to_array($xml->entry, false);
foreach ($entries as $index => $val)
{
    $gameTitle = $val->title;
    echo "<p>$gameTitle</p><p>Index = $index</p>";

}

Demo。实际上你不必须使用你也可以计算的功能:

$index = 0;
foreach ($xml->entry as $val)
{
    echo "<p>{$val->title}</p><p>Index = $index</p>";
    $index++;
}

默认情况下,$key(如示例代码中所示)是XML元素的标记名。所以默认情况下你不能将它用作索引号。