I want to modify XML values (of the file) using simpleXML in a foreach loop.
My XML look like that :
<a>
<b id="first">
<c></c>
<d></d>
</b>
<b id="second">
<c></c>
<d></d>
</b>
<b id="third">
<c></c>
<d></d>
</b>
And my php look like that :
$xml = simplexml_load_file('myfile.xml');
$idOfB = 'first'; // the id of b and I want to modify the children nodes of that
foreach($xml->a->b as $node) {
foreach($node->attributes() as $id => $value) {
if((string)$value == $idOfB) {
// Something there I guess...
// I want to change the value of c and d of this node
}
}
}
$xml->asXML();
I have tried and searched quite a lot without any luck.
Your testing file suppose to be like ---
<?xml version="1.0" encoding="UTF-8"?>
<a>
<b id="first">
<c>Abhishek</c>
<d/>
</b>
<b id="second">
<c/>
<d/>
</b>
<b id="third">
<c/>
<d/>
</b>
</a>
here abhishek will be replaced by Nishant
<?php
$xml = simplexml_load_file("testingxml.xml");
$idOfB = 'first'; // the id of b and I want to modify the children nodes of that
foreach($xml->b as $node) {
foreach($node->attributes() as $id => $value) {
if((string)$value == $idOfB) {
$node->c = 'Nishant';
$node->d = 'Tyagi';
// Something there I guess...
// I want to change the value of c and d of this node
}
}
//$finobjArr[] = $node;
}
//$xmlobj = $finobjArr;
file_put_contents("testingxml.xml", $xml->saveXML());
////$xml->asXML("testingxml.xml");
//print($xml->asXML("testingxml.xml"));
?>
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.