对于
等结构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
等等;即。
[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
答案 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元素的标记名。所以默认情况下你不能将它用作索引号。