I have an XML structure that looks like this:
<?xml version="1.0"?>
<survey>
<responses>0</responses>
<question>
<title>Some survey question</title>
<answer>
<title>Answer 1</title>
<responses>0</responses>
</answer>
<answer>
<title>Answer 2</title>
<responses>0</responses>
</answer>
...
</question>
...
</survey>
I want to increment the <responses> values for answers that match the values in a $response array. Here’s how the $response array is structured:
$response = array(
'sid' => session_id(),
'answers' => array(
$_POST['input1'],
$_POST['input2'],
...
)
);
I have a SimpleXMLElement called $results for my survey xml file. Here’s how I’m going about it:
$results = simplexml_load_file($surveyResultsFile);
$i = 1;
foreach($response->answers as $answer) {
$r = $results->xpath("question[$i]/answer[title='$answer']/responses");
$r = $r[0];
$r = intval($r) + 1;
$i++;
}
file_put_contents($surveyResultsFile, $results->asXML());
My results aren’t being saved after incrementing the value of $r. Any ideas on what I’m doing wrong? Thanks!
There are several errors in your script, which explains why it doesn’t work. First, your
$responsearray doesn’t seem right. Did you really intend to use variables in place of keys? Tryprint_r($response);and see if it’s really what you want.You can select the nth
<question/>using the array notation (0-based) as inOnce you get the right question, all you need to do is verify that it does indeed contain the suggested answer with XPath. Then only, you can increment the value of
<responses/>. Also, you have to escape special characters such as<or", which would make your XPath query fail.Finally, you can use
asXML()to actually save the file (nofile_put_contents()needed here.) I assume that your$surveyResultsis a typo and that you meant$surveyResultsFile.