Inserting to XML

Hey guys,

Long time since I have written on here and a very long time since I have done any web development.

I am writing a small web app and have the following question.

I have an XML file like so:

<?xml version="1.0"?>
<question_list>
	<question>
		<id>
			1
		</id>
		<text>
			What is a Cat?
		</text>
	</question>
	<question>
		<id>
			2
		</id>
		<text>
			What is your name?
		</text>
	</question>
</question_list>

I am learning how to extract the data from the XML file which is fine as their are loads of tutorials on that but how would I for example insert a new question into the XML?

Thanks

By using the SimpleXML class

Specifically, the addChild method

ok, thanks, I ahve the following line:

$question->addChild('text', '$question_text');

When that is run the actual text “$question_text” is put into the xml file and is not replaced by the value of that variable. How do I get the value to replace the name of the variable?

To modify an existing value, rather than add a new one, you would use a standard assignment operator.

The documentation for SimpleXML has some examples of basic usage that shows the following code for setting values


<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);

$xml->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $xml->asXML();
?>

I think you misunderstood what i meant, I need to how to to get the $text_question variable converted into it’s actual value to be put into the file. Currently the name of the variable itself is being inserted

Removing the single quotes from around it will do that nicely.

$question->addChild(‘text’, $question_text);

Does that do it?

Yes.

Thanks guys. I have a lecture now but will try it in my break afterwards

thanks again

sry, really should refresh more often, in my to do list in all :S