Skip to content
Advertisement

How to insert data in a XML sub tag

let’s suppose that i have this tag

<root>
<foo> </foo>
</root>

with this html form

<form action="foo.php method="post">
<input type="text" name="something">
<input type="submit" name="ok">
</form>

if I want to insert data I do

<?php
if(isset($_POST['ok'])) {
$data=simplexml_load_file('foo.xml') or die('error');

if(isset($_POST['something'])) {    
    $data->foo= $_POST['something'];
} 

it work nicely without any problem now if we want to insert a data in the sub tag

<root>
  <foo>
   <test></test>
  </foo>
</root>

I thought we should do something like

if(isset($_POST['something'])) {    
    $data->foo->test= $_POST['something'];
} 

let’s suppose that we have “hello” in $_POST['something'] variable I expected to have something like

<root>
  <foo> 
   <test>Hello</test>
  </foo>
</root>

but it does not work

Advertisement

Answer

<?php
    $root=simplexml_load_file("file.xml") or die("Error"); // first we load the file
    if(isset($_POST['ok'])){ // if we validate the form
    $something= $_POST['something']; // we recover the data with POST
    // let assume that we have 'hello' inside $something
    $root->foo->test = $something; //then we send the data to the xml file
    $root->asXML('foo.xml');
}

the output

<?xml version="1.0"?>
<root>
  <foo>
   <test>Hello</test>
  </foo>
</root>

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement