Reputation: 477
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:
Any help would be appreciated.
Upvotes: 2
Views: 5056
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
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
Reputation: 51950
Get the server object/array where $serverName = "Google"
// An array of all <server> elements with the chosen name
$googles = $servers->xpath('server[name = " Google "]');
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';
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