如何使用PHP将子项添加到新创建的XML节点

时间:2018-04-07 19:05:26

标签: php xml simplexml

我正在尝试使用simpleXml的addChild()将子项添加到新创建的节点,但它给了我一个例外:

Warning: SimpleXMLElement::addChild()[simlexmlelement.addchild]: Cannot add child. Parent is not a permanent member of the XML tree in (file address) on line (line number)

我得到了多次,因为我的代码的重要部分是:

<?php

  $xml = simplexml_load_file(".db.xml") or die("Sorry, no database file found, we will solve it as soon as possible.");

  if($xml->$name->getName() == $name) {
    echo "We're sorry, but this account name already exists. Underneath is a table with your signup data anyways. We also sent you an email if you are going to retry later.";
  } else {
    $xml->db->addChild($name);
    $xml->$name->addChild("email", $email);
    $xml->$name->addChild("day", $day);
    $xml->$name->addChild("month", $month);
    $xml->$name->addChild("year", $year);
  }
?>

这是我的美化XML代码:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <db>
    <example>
      <email>example@email.com</email>
      <day>01</day>
      <month>01</month>
      <year>1975</year>
    </example>
  </db>
</body>

我在这里做错了什么?

注意:

我知道变量的值不是问题,因为所有变量都在我为页面制作的数据表中显示了正确的值。

1 个答案:

答案 0 :(得分:1)

您应该将子项添加到引用中,如下所示:

$nametag = $xml->db->addChild($name);
$nametag->addChild("email", $email);
$nametag->addChild("day", $day);
$nametag->addChild("month", $month);
$nametag->addChild("year", $year);

在这里阅读更多内容: http://php.net/manual/ro/simplexmlelement.addchild.php

示例nr.1

<强>更新

这里我用输出测试的代码,所以你可以看到它实际上将标签添加到最终的xml结构中:

$xml = simplexml_load_file("db.xml") or die("Sorry, no database file found, we will solve it as soon as possible.");
$name = "a";
$email = "b";
$day = "c";
$month = "d";
$year = "e";
if($xml->$name->getName() == $name) {
    echo "We're sorry, but this account name already exists. Underneath is a table with your signup data anyways. We also sent you an email if you are going to retry later.";
} else {
    $tagname = $xml->db->addChild($name);
    $tagname->addChild("email", $email);
    $tagname->addChild("day", $day);
    $tagname->addChild("month", $month);
    $tagname->addChild("year", $year);
}
var_dump($xml->asXML()); 

更新2

要将xml保存到文件末尾添加:

$xml->asXML("db.xml"); // this would overwrite your old file

在这里查看: http://php.net/manual/en/simplexmlelement.asxml.php