JPMD JPMD - 6 months ago 7
PHP Question

How to recover a item from a XML tag

I am stuck with getting the value from a XML element list. I wonder if someone here could help? Thanls in advance.

Here is the problem. I have this XML element:

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


And I need to print the elements in the tag. For example, I need to print "Option 1", "Option 2", ... , "Option 5" in a webpage by the order they were selected by the user.

If i use this code:

$SequenceQuestionNumber = 1;

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

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


I get as answer values "0", "1", "2", "3" and "4". But what I need is not the 'userDefinedPosition" but rather the text associated with it. For "0" I need to print "Option 1", for "1" I need "Option 2", for "3" I need "Option 2", etc...

I have tried to build an array like this:

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


but I just get blanks (nothing) printed

I guess what is messing my reference is the userDefinedPosition inside the tag, but I am not sure on how to get the labels instead of the index numbers.

Any comments will be greatly appreciated.
Thanks!
JPMD

Answer

You could simply do what you want to do with Xpath in a cleaner and more concise way like this

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

   }

?>

This outputs

Option 1
Option 2
Option 3
Option 4
Option 5

For more reference you can read the docs http://php.net/manual/en/simplexmlelement.xpath.php

Comments