複数の.xmlファイル(001.xml、002.xml、002.xmlなど)を取得し、データベーステーブルから新しい子情報を追加してから、変更した情報を新しいファイルとしてローカルに保存しようとしています。
データベースに多くの行がありますが、SimpleXMLElement関数を使用すると、スクリプトが複数回実行されるのを防ぐことができます。
コードの簡略化されたバージョンは次のとおりです。
$query=mysql_query('SELECT id FROM `table`');
while($row = mysql_fetch_array($query))
{
$contents = file_get_contents('path_to_url'.$row[0]);
$xml = new SimpleXMLElement($contents);
// Append information to xml data
for($i=0; $i < count($xml->parent->children->child); $i++)
{
$query=mysql_query('
SELECT `age`
FROM `table2`
WHERE `name` = '.$xml->parent->children->child[$i]->name
);
$childage = mysql_fetch_array($query);
$xml->parent->children->child[$i]->addChild('age',$childage[0]);
}
$file = 'id'.$row[0].'.xml';
file_put_contents($file, $xml->asXML());
}
元のサンプル.xmlデータは次のとおりです。
001.xml
<parent>
<children>
<child>
<name>herp</name>
</child>
<child>
<name>derp</name>
</child>
</children>
<parent>
002.xml
<parent>
<children>
<child>
<name>manny</name>
</child>
<child>
<name>joe</name>
</child>
<child>
<name>jack</name>
</child>
</children
</parent>
これが出力になります(ループが停止するため、002.xmlは書き込まれないことに注意してください)
001.xml
<parent>
<children>
<child>
<name>herp</name>
<age>10</age>
</child>
<child>
<name>derp</name>
<age>12</age>
</child>
</children>
</parent>