【问题标题】:Its a simple loop but I do not know how to do it它是一个简单的循环,但我不知道该怎么做
【发布时间】:2013-02-21 09:41:57
【问题描述】:

我需要解析以下 xml,但是当我使用我的代码时,它只读取第一个 p 标签,我知道它是一个简单的循环,但我很困惑。

 <s>
 <j u="here1"/>
   <p v="here1_1"/>
   <p v="here1_2"/>
   <p v="here1_3"/>
   <p v="here1_4"/>
   <p v="here1_5"/>
   <p v="here1_6"/>
</s>
<s>
 <j u="here2" />
   <p v="here2_1"/>
   <p v="here2_2"/>
   <p v="here2_3"/>
   <p v="here2_4"/>
   <p v="here2_5"/>
   <p v="here2_6"/>
</s>

我的代码

$xml = simplexml_load_string($myXml);
foreach ($xml->s as $tags) {
        echo $tags->j->attributes()->u . " ";
        echo $tags->p->attributes()->v . " ";
    }

结果是 >>> here1 here1_1 here2 here2_1

但结果应该是here1 here1_1 ..... here1_6 here2 here2_1 ..... here2_6

【问题讨论】:

    标签: php xml-parsing


    【解决方案1】:

    也许是这样的?

    $xml = simplexml_load_string($myXml);
    foreach ($xml->s as $tags) foreach ($tags as $tag) {
        echo $tag->attributes()->u . " "; // $tag['u'] you can access attributes like this too
        echo $tag->attributes()->v . " "; // $tag['v']
    }
    

    这应该给你

    here1
    here1_1 
    here1_2 
    here1_3 
    here1_4 
    here1_5 
    here1_6 
    here2 
    here2_1 
    here2_2 
    here2_3 
    here2_4 
    here2_5 
    here2_6 
    

    【讨论】:

      【解决方案2】:

      因为有多个 p 标签,你需要遍历 p 标签

      $xml = simplexml_load_string($myXml);
      foreach ($xml->s as $tags) {
              echo $tags->j->attributes()->u . " ";
              foreach($tags->p as $ptags){
                  echo $ptags->attributes()->v . " ";
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2015-12-26
        • 1970-01-01
        • 2016-05-30
        • 2019-04-15
        • 2022-01-08
        • 2014-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多