2012-03-24 78 views
1

我哈瓦一個XML文件是這樣的:在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> 

我試圖以循環中的所有領域,但是當我得到答案點它dosent循環中的所有答案

任何提示我怎麼能管理呢?

我使用:

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

爲了得到結果。

Thanx提前 帕特里克

+0

你是如何循環的領域?在代碼中?使用XSLT? – 2012-03-24 09:47:30

+0

在你的代碼中是否有'foreach($ entry-> answers-> answer作爲$ answer)? – Tomalak 2012-03-24 09:52:09

回答

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

0

您可以通過使用DOM文檔()來實現這個目的。

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