Nasco Bozhkov
Nasco Bozhkov

Reputation: 477

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.

Upvotes: 2

Views: 5056

Answers (3)

Nishad Up
Nishad Up

Reputation: 3615

The below code will help you to modify the xml and get back in a text formate.

$xml_obj = new SimpleXMLElement($xml);

foreach ($xml_obj->server as $value) {
    /*Do something here*/
}
$doc = new DOMDocument();
$doc->formatOutput = TRUE;
$doc->loadXML($xml_obj->asXML());
$output = $doc->saveXML();

Upvotes: 0

anon
anon

Reputation:

Load the XML file using simplexml_load_file, loop through the <server> nodes, check if the is Google, and if it is True, change the .

$xml=simplexml_load_file("simple.xml");
foreach($xml->server as $server){
    ($server->name == trim("Google")) ? $server->address = "http://www.google.co.uk" : "";
}

Upvotes: 1

salathe
salathe

Reputation: 51950

  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

Upvotes: 7

Related Questions