代码之家  ›  专栏  ›  技术社区  ›  mko

获取simplexmlement中foreach循环中的子索引

  •  3
  • mko  · 技术社区  · 15 年前
    <?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>
    

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

    在php呈现页面之后 <a href="#slide-$key"> 返回 <a href=#slide-item> 我要$key知道号码,

    5 回复  |  直到 15 年前
        1
  •  6
  •   Pekka    15 年前

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

     $index = 0;
     $xml = simplexml_load_file('post.xml');
    
     foreach($xml->item as $item )
       {
           ....
           $index++;
        }
    
        2
  •  6
  •   salathe    15 年前

    你可以用 SimpleXMLElement::xpath <item> 元素,然后根据需要访问数组的键。

    foreach ($xml->xpath('/items/item') as $key => $item) 
    
        3
  •  0
  •   Sarfraz    15 年前

    如果使用heredocs格式,则需要将变量包装在大括号中:

    <a href="#slide-{$key}">
      <h3>{$item->title}</h3>
    </a>
    
        4
  •  0
  •   Phill Pafford    15 年前

    Heredoc

    <a href="#slide-{$key}">
    
        5
  •  0
  •   Shikiryu DhruvJoshi    15 年前

    你可以用 for foreach

    $item = $xml->item;
    $howMany = count($item);
    for($i = 0; $i < $howMany; $i++){
    echo <<<HTML
                        <li>
                        <div class="published">
                            <span class="day">13</span>
                            Sep 2010
                        </div>
    
                        <div class="summary">
                        <a href="#slide-$i">
                                <h3>$item->title</h3>
                        </a>
                        </div>
                        </li>
    
    HTML;
    }