2

I'm trying to create a form that will let you edit the contents of an xml tag. i currently have a form.php:

<?php
$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;
?>

<form method="post">
    <textarea name="name"><?php echo $welcome ?></textarea>
    <br>
    <input type="submit" name="submit" value="submit">
</form>

<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$xml->asXML());
fclose($handle);
}
?>

and welcome.xml:

<welcome>
    <item>
        <name>$welcome</name>
    </item>
</welcome>

when i press submit it doesn't save what's entered, it just refreshes the page and deletes whatever the value in the xml file was before..

UPDATE

The form works now, but I've added a reset button, i need it to clear the xml file so it only has the <welcome> tags. I've changed $data->item->name=$_POST['welcome']; to $data=''; but it deletes the text and keeps the tags still.

1 Answer 1

4

You can do it with simplexml.

To read data from xml:

$data = simplexml_load_file('welcome.xml');

$welcome = $data->item[0]->name;

And to write data:

$data = simplexml_load_file('welcome.xml');

$data->item[0]->name = $_POST['welcome'];

$handle = fopen("welcome.xml", "wb"); 
fwrite($handle, $xml->asXML());
fclose($handle);

EDIT: For the question in the comment:

<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}

$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;

?>

<form method="post">
    <textarea name="name"><?php echo $welcome ?></textarea>
    <br>
    <input type="submit" name="submit" value="submit">
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

one last thing, i've added another button to remove the <item><name></name></item> parts so the xml file just has <welcome> in it, but it just clears the text, not the tags, I changed this $data->item->name=$_POST['welcome']; to this $data='';
use unset($data->item); instead of $data='';

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.