如何从XML标记中恢复项目

时间:2016-05-10 22:55:04

标签: php xml

我很难从XML元素列表中获取值。我想知道这里有人可以提供帮助吗?

这是问题所在。我有这个XML元素:

<sequenceQuestion status="correct" maxPoints="10" maxAttempts="1" awardedPoints="10" usedAttempts="1">
  <direction>Order the following options</direction>
  <answers>
    <answer userDefinedPosition="0">Option 1</answer>
    <answer userDefinedPosition="1">Option 2</answer>
    <answer userDefinedPosition="2">Option 3</answer>
    <answer userDefinedPosition="3">Option 4</answer>
    <answer userDefinedPosition="4">Option 5</answer>
  </answers>
</sequenceQuestion>

我需要打印标签中的元素。例如,我需要按照用户选择的顺序在网页中打印“选项1”,“选项2”,......,“选项5”。

如果我使用此代码:

$SequenceQuestionNumber = 1;

foreach($answer_group->answers->answer as $userSequenceQuestion){

if($status!="notAnswered" && isset($userSequenceQuestion->attributes()->userDefinedPosition)) {
    $userDefinedPosition = (string)$userSequenceQuestion->attributes()->userDefinedPosition;
    $values .= "\"" . $userDefinedPosition . "\", ";

我得到答案值“0”,“1”,“2”,“3”和“4”。但我需要的不是'userDefinedPosition'而是与之相关的文本。对于“0”我需要打印“选项1”,对于“1”我需要“选项2”,对于“3”我需要“选项” 2“等等......

我试图像这样构建一个数组:

$answers = (array)$userSequenceQuestion->answer;
$values .= "\"" . $answers[$userDefinedPosition] . "\", ";

但我只是打印空白(没有)。

我想在我的引用中弄乱的是标签内的userDefinedPosition,但我不确定如何获取标签而不是索引号。

2 个答案:

答案 0 :(得分:0)

你可以用更简洁的方式用Xpath完成你想做的事情

<?php

$string = <<<S
<sequenceQuestion status="correct" maxPoints="10" maxAttempts="1" awardedPoints="10" usedAttempts="1">
  <direction>Order the following options</direction>
  <answers>
    <answer userDefinedPosition="0">Option 1</answer>
    <answer userDefinedPosition="1">Option 2</answer>
    <answer userDefinedPosition="2">Option 3</answer>
    <answer userDefinedPosition="3">Option 4</answer>
    <answer userDefinedPosition="4">Option 5</answer>
  </answers>
</sequenceQuestion>
S;

$results = new SimpleXMLElement($string);

foreach ($results->xpath("answers")[0]->children() as $child) {
   echo $child . "<br />";

   }

?>

此输出

Option 1
Option 2
Option 3
Option 4
Option 5

有关详情,请参阅文档http://php.net/manual/en/simplexmlelement.xpath.php

答案 1 :(得分:0)

确定。所以我明白了。谢谢所有有助于回答的人。这是编写用户答案排序的代码:

if($answer_group->getName()=="sequenceQuestion") { //SEQUENCE QUESTION

$SequenceQuestionNumber = 1;

foreach($answer_group->answers->answer as $userSequenceQuestion){

if($status!="notAnswered" && isset($userSequenceQuestion->attributes()->userDefinedPosition)) {
$userDefinedPosition = (int)$userSequenceQuestion->attributes()->userDefinedPosition;
$answers = (string)$answer_group->answers->answer[$userDefinedPosition];
$values .= "\"" . $answers . "\", ";
} else {
$values .= "\"" . $status_notAnswered . "\", ";
}

$SequenceQuestionNumber++;
}