在xml文件中循环循环?

时间:2012-03-24 09:45:16

标签: php xml simplexml

我有一个像这样的xml文件:

<name>
    <entry>
        <date>2012-03-18 13:53:23</date>
        <ID>1</ID>
        <category>questions</category>
        <question>who are you?</question>
    <answers>
        <answer text='a man' id='1'/>
        <answer text='a woman' id='2'/>
        <answer text='an animal' id='3'/>
        <answer text='an alien' id='4'/>
    </answers>
        <author>Gorge</author>
    </entry>
</name>

我正在尝试循环所有字段,但是当我到达答案点时,它会循环所有答案

任何提示我如何管理?

我正在使用:

foreach($xml->entry as $entry){
echo "<p>";
echo "<strong>Author:</strong> ".$entry->author."<br/>";
echo "</p>";
}

获得结果。

提前完成 帕特里克

2 个答案:

答案 0 :(得分:1)

好像你正在使用SimpleXML。你可能想要沿着这些方向做点什么:

foreach($xml->entry as $entry){
  //iterating through your entry-elements
  echo $entry->question . '<br />';

  foreach($entry->answers->answer as $answer) {
    //iterating through the anwers of the entry-element
    echo $answer['text'] . '<br />';
  }
}

输出:

  你是谁?

     
      
  • 一个男人
  •   
  • 一个女人
  •   
  • 动物
  •   
  • 外星人
  •   

http://codepad.org/Nfbo4l59

答案 1 :(得分:0)

您可以使用DOMDocument()类来完成此操作。

    <?php
    $xml="<name>
        <entry>
            <date>2012-03-18 13:53:23</date>
            <ID>1</ID>
            <category>questions</category>
            <question>who are you?</question>
        <answers>
            <answer text='a man' id='1'/>
            <answer text='a woman' id='2'/>
            <answer text='an animal' id='3'/>
            <answer text='an alien' id='4'/>
        </answers>
            <author>Gorge</author>
        </entry>
    </name>
    ";
    $dom=new DOMDocument();
    $dom->loadXML($xml);

    foreach($dom->getElementsByTagName('entry') as $tagentry)
    {
        foreach($tagentry->getElementsByTagName('answers') as $taganswers)
        {
            foreach($taganswers->getElementsByTagName('answer') as $taganswer)
            {
                $taganswer_array[]=$taganswer->getAttribute('text');
            }
        }
    }

    echo "<pre>";
    print_r($taganswer_array);
    echo "</pre>";
    ?>

输出:

Array(

   [0] => a man  

   [1] => a woman 

   [2] => an animal 

   [3] => an alien