たとえば同名の要素が反復し、属性(例:「id」)で判別する次のような XML がある場合。
<root>
<location id="kanagawa" population="879万">
<capital name="yokohama"/>
</location>
<location id="tokyo" population="1257万">
<capital name="tokyo"/>
</location>
<location id="fukuoka" population="504万">
<capital name="fukuoka"/>
</location>
</root>
これを php(SimpleXML)で編集しようとするなら、一般的には(1)「先頭から n 番目」という指定、または(2)attribute (id)の値で指定、という方法を思いつく。
後者の方法を覚え書き。
$file = 'sample.xml';
if($root = simplexml_load_file($file)){
$ID = $_POST["id"];
foreach ($root->location as $pref) {
$c = 0;
if ($pref['id'] == $ID) {
$pref[$c]["population"] = $_POST["population"];
$pref[$c]->capital["name"] = $_POST["name"];
}
$c++;
}
}
$root -> asXML($file);
はまりにハマって時間をドブに捨てた。