在simpleXMLElement中获取foreach循环中的子索引

mko*_*mko 3 php foreach key

<?xml version="1.0" encoding="utf-8"?>
<items>
  <item>
    <title>This is title1</title>
    <desc>This is desc1</desc>
    <image></image>
    <tudou></tudou>
  </item>
  <item>
    <title>This is title2</title>
    <desc>This is desc2</desc>
    <tudou>55362137</tudou>
  </item>
  <item>
    <title>This is title3</title>
    <desc>This is desc4</desc>
  </item>
</items>
Run Code Online (Sandbox Code Playgroud)

这是我的PHP代码:

<div class="nav">
    <ul>
        <?php
                $xml = simplexml_load_file('post.xml');
                //print_r($xml);
                foreach($xml->item as $key=>$item )
                {
                    echo <<<HTML
                    <li>
                    <div class="published">
                        <span class="day">13</span>
                        Sep 2010
                    </div>

                    <div class="summary">
                    <a href="#slide-$key">
                            <h3>$item->title</h3>
                    </a>
                    </div>
                    </li>

HTML;
                }
            ?>
        </ul>
    </div>
Run Code Online (Sandbox Code Playgroud)

在php渲染页面后,<a href="#slide-$key">返回<a href=#slide-item>.我想要$ key获取其中的数量,那么如何获得?

Pek*_*ica 6

这是因为simpleXML结构不是普通数组,而是没有数组索引的迭代器.

除了使用变量手动跟踪之外,我不知道任何其他解决方案:

 $index = 0;
 $xml = simplexml_load_file('post.xml');

 foreach($xml->item as $item )
   {
       ....
       $index++;
    }
Run Code Online (Sandbox Code Playgroud)


sal*_*the 5

您可以使用SimpleXMLElement::xpath返回<item>元素数组,然后根据需要访问数组的键.

foreach ($xml->xpath('/items/item') as $key => $item) 
Run Code Online (Sandbox Code Playgroud)