tags:

views:

42

answers:

0

PHP editing a XML file?

So i have an XML file that looks like this

<?xml version="1.0" encoding="iso-8859-1"?>
<employees>
  <employee>
    <name>Mark</name>
    <age>27</age>
    <salary>$5000</salary>
  </employee>
  <employee>
    <name>Jack</name>
    <age>25</age>
    <salary>$4000</salary>
  </employee>
</employees>

I want to perform 2 actions.

1)be able to edit their age and salery
2)add an employee

My code looks a little like this

    <?php

  $doc = new DOMDocument();

  $doc->load( 'employees.xml' ); 
  $doc->formatOutput = true;

  $r = $doc->createElement( "employees" );
  $doc->appendChild( $r );

  foreach( $employees as $employee )
  {
  $b = $doc->createElement( "employee" );

  $name = $doc->createElement( "name" );
  $name->appendChild(
  $doc->createTextNode( $employee['name'] )
  );
  $b->appendChild( $name );

  $age = $doc->createElement( "age" );
  $age->appendChild(
  $doc->createTextNode( $employee['age'] )
  );
  $b->appendChild( $age );

  $salary = $doc->createElement( "salary" );
  $salary->appendChild(
  $doc->createTextNode( $employee['salary'] )
  );
  $b->appendChild( $salary );

  $r->appendChild( $b );
  }

  echo $doc->saveXML();
  $doc->save("write.xml")
  ?> 

I am able to get it to append on to the end of the XML file however I can't get it to insert inside of the tag :(.