2012-03-24 7 views
1

i eine XML-Datei wie folgt hava:Schleife eine Schleife in einer XML-Datei?

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

und ich versuche, alle Felder Schleife, aber wenn ich auf die Antwort Punkt dosent es Schleife alle Antworten

irgendwelche Tipps, wie kann ich das schaffen?

Ich verwende:

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

Für das Ergebnis.

Thanx im Voraus Patrik

+0

Wie Looping Sie die Felder? In Code? Mit XSLT? –

+0

Gibt es eine 'foreach ($ entry-> answers-> answer als $ answer) irgendwo in deinem Code? – Tomalak

Antwort

1

Scheint, wie Sie SimpleXML verwenden. Sie wollen wahrscheinlich etwas in dieser Richtung tun:

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 />'; 
    } 
} 

Ausgang:

wer du bist?

  • ein Mann
  • eine Frau
  • ein Tier
  • ein Ausländer

http://codepad.org/Nfbo4l59

0

Sie dies tun können DOMDocument() der Klasse unter Verwendung.

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

Ausgabe ::

Array(

    [0] => a man 

    [1] => a woman 

    [2] => an animal 

    [3] => an alien 

)