我想在foreach循环中使用simpleXML修改(文件的)XML值。
我的XML看起来像这样:
<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>
我的php看起来像那样:
$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();
我没有运气就尝试过很多次。
答案 0 :(得分:4)
您的测试文件假设为---
<?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>
这里abhishek将被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"));
?>