0

There is a XML file with following content :

<StaticDataRequest>
   <Header>
      <Code>XXXX</Code>
      <Username>XXXX</Username>
      <Password>XXXX</Password>
   </Header>
   <Body>
      <GetStaticData>countries</GetStaticData>
   </Body>
</StaticDataRequest>

I need to change Code, Username, Password values of the above file and save it.

So, I read that file by following command :

$xml = simplexml_load_file("country_request.xml");

And I changed elements values as below:

$xml->Header->Code = 'myCode';
$xml->Header->Username  = 'myUsername';
$xml->Header->Password  = 'myPassword';

Now, $xml is an object with following structure:

SimpleXMLElement Object
(
    [Header] => SimpleXMLElement Object
        (
            [Code] => myCode
            [Username] => myUsername
            [Password] => myPassword
        )

    [Body] => SimpleXMLElement Object
        (
            [GetStaticData] => countries
        )
)

The Question

The main question is how can I write $xml into a XML file with XML structure?

That would be like this:

<StaticDataRequest>
       <Header>
          <Code>myCode</Code>
          <Username>myUsername</Username>
          <Password>myPassword</Password>
       </Header>
       <Body>
          <GetStaticData>countries</GetStaticData>
       </Body>
</StaticDataRequest>
Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125

1 Answers1

0

simplexml_load_file returns a SimpleXMLElement object. If you look through the documentation you will find this:

public mixed asXML ([ string $filename ] )

In other words:

$file = "country_request.xml";
$xml = simplexml_load_file($file);

// Do you stuff here...

if ($xml->asXML($file)) {
    echo 'Saved!';
} else {
    echo 'Unable to save to file :(';
}
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
  • It worked tnx, But first line of `$file` contains its xml version ``. can I write into `$file` without XML version at the first line? – Hamed Kamrava Mar 01 '15 at 08:03
  • @user41888 XML files should have a version. But if you really want it gone then [this question](https://stackoverflow.com/questions/5947695/remove-xml-version-tag-when-a-xml-is-created-in-php) should help you out. – Sverri M. Olsen Mar 01 '15 at 08:08