这是一个简单的循环,但我不知道该怎么做

时间:2013-02-21 09:41:57

标签: php xml-parsing

我需要解析下面的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>

mycode

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

结果是&gt;&gt;&gt; here1 here1_1 here2 here2_1

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

2 个答案:

答案 0 :(得分:2)

也许是这样的?

$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 

答案 1 :(得分:0)

因为有多个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 . " ";
        }
    }
相关问题