dongyuan1160 2014-06-30 11:20
浏览 120
已采纳

PHP SimpleXML显示不规则的子节点

I have an XML file with an irregular amount of child nodes, and would like to display the question and child nodes. The display for the questions is correct, but I am getting stuck on properly displaying the child nodes.

<Survey>
  <Question ID="1">
    <QuestionText>Question Number 1</SurveyQuestionText>
     <AnswerText>Answer 1</SurveyAnswerText>
     <AnswerText>Answer 2</SurveyAnswerText>
     <AnswerText>Answer 3</SurveyAnswerText>
     <AnswerText>Answer 4</SurveyAnswerText>
     <AnswerText>Answer 5</SurveyAnswerText>
  </Question>   
  <Question ID="2">
    <QuestionText>Question Number 2</SurveyQuestionText>
     <AnswerText>Answer 1</SurveyAnswerText>
     <AnswerText>Answer 2</SurveyAnswerText>
     <AnswerText>Answer 3</SurveyAnswerText>
  </Question>   
  <Question ID="3">
    <QuestionText>Question Number 3</SurveyQuestionText>
     <AnswerText>Answer 1</SurveyAnswerText>
     <AnswerText>Answer 2</SurveyAnswerText>
     <AnswerText>Answer 3</SurveyAnswerText>
     <AnswerText>Answer 4</SurveyAnswerText>
  </Question>   
</Survey>

Here is my code so far

$xml_url = "questions.xml";
$xml = simplexml_load_file($xml_url); 

$x = 1;


foreach($xml->children() as $question) {
   echo $x . ".) " . $question->QuestionText . "
";
   $numAnswers = $question->AnswerText->count();
   echo "count: " . $numAnswers . "
";

   //insert code for display AnswerText

   $x++;    
}

Here is my output so far:

1.) Question Number 1
count: 5
2.) Question Number 2
count: 3
3.) Question Number 3
count: 4
  • 写回答

2条回答 默认 最新

  • duanjieyi6582 2014-06-30 11:26
    关注

    Just add a second inner foreach for the answers:

    foreach($xml->children() as $question) {
       echo $x . ".) " . $question->QuestionText . "
    ";
       $numAnswers = $question->AnswerText->count();
       echo "count: " . $numAnswers . "
    ";
    
       //insert code for display AnswerText
       foreach($question->AnswerText as $answers)
           echo $answer;
    
       $x++;    
    }
    

    SimpleXML has a load of very usefull access mechanisms. For example the Iterator, which is used here.

    Read all of it here: http://www.php.net/manual/en/simplexml.examples-basic.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?