我的 XML 开始看起来像这样:
<user>
<entry>
<date>December 8, 2012, 6:27 am</date>
<height>73</height>
<weight>201</weight>
</entry>
</user>
我想向它添加“条目”,使其看起来像这样
<user>
<entry>
<date>December 8, 2012, 6:27 am</date>
<height>73</height>
<weight>201</weight>
</entry>
<entry>
<date>December 9, 2012, 6:27 am</date>
<height>73</height>
<weight>200</weight>
</entry>
</user>
我正在使用的代码将所有内容都包含在第一个<entry>...</entry>
标签中。这是我的PHP代码。
$file = 'users/'.$uID.'data.xml';
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");
// original
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
// get document element
$root = $xml->documentElement;
$fnode = $root->firstChild;
//add a node
$ori = $fnode->childNodes->item(3);
$today = date("F j, Y, g:i a");
$ydate = $xml->createElement("date");
$ydateText = $xml->createTextNode($today);
$ydate->appendChild($ydateText);
$height = $xml->createElement("height");
$heightText = $xml->createTextNode($_POST['height']);
$height->appendChild($heightText);
$weight = $xml->createElement("weight");
$weightText = $xml->createTextNode($_POST['weight']);
$weight->appendChild($weightText);
$book = $xml->createElement("entry");
$book->appendChild($ydate);
$book->appendChild($height);
$book->appendChild($weight);
$fnode->insertBefore($book,$ori);
$xml->save('users/'.$uID.'data.xml') or die("Error");
如何调整我的代码,以便将我的条目放在正确的位置?谢谢!