Search code examples
phpxmlxml-parsingsimplexml

Editing XML Nodes through SimpleXML PHP


I know similar questions have been asked several times, but I can't find a solution to the following:

I've got a simple XML file: servers.xml

<servers>

    <server>
        <name> Google </name>
        <address>http://www.google.com</address>
    </server>

    <server> 
        <name> Yahoo </name>
        <address>http://www.yahoo.com</address>
    </server>

    <server>
        <name> Bing </name>
        <address>http://www.bing.com</address>
    </server>

</servers>

Now, I'm trying to get the <server> node which has a name of "Google" for example, and then change the address tag. I have no idea how to go about it using SimpleXML. So an example scenario would the following:

  1. Get the server object/array where $serverName = "Google"
  2. Edit the server's address field to something different like http://www.google.co.uk
  3. Write the changes back to the XML file.

Any help would be appreciated.


Solution

    1. Get the server object/array where $serverName = "Google"

      // An array of all <server> elements with the chosen name
      $googles = $servers->xpath('server[name = " Google "]');
      
    2. Edit the server's address field to something different like http://www.google.co.uk

      //Find a google and change its address
      $google->address = 'http://www.google.co.uk';
      
    3. Write the changes back to the XML file.

      $servers->saveXML('path/to/file.xml');
      

    Full example

    $servers = simplexml_load_file('path/to/file.xml');
    $googles = $servers->xpath('server[name=" Google "]');
    foreach ($googles as $google) {
        $google->address = 'http://www.google.co.uk';
    }
    $servers->saveXML('path/to/file.xml');
    

    More info