gpt4 book ai didi

php - 使用 PHP 添加 XML 节点

转载 作者:行者123 更新时间:2023-12-04 05:20:11 26 4
gpt4 key购买 nike

我的 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");

如何调整我的代码,以便将我的条目放在正确的位置?谢谢!

最佳答案

您需要将条目附加到根元素用户:

<?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;

//add a node
$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);

$root->appendChild($book);
$xml->save('users/'.$uID.'data.xml') or die("Error");
?>

关于php - 使用 PHP 添加 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13775057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com