0

对于诸如

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,即0, 1,2等;IE

[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

4

1 回答 1

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

}

演示。实际上,您不必使用该功能,也可以只计算

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

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

于 2013-02-06T00:44:30.923 回答