简体   繁体   中英

PHP: How do I write XML object into a XML file

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>

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 :(';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM