Php 使用SimpleXML从html附加到xml的问题

Php 使用SimpleXML从html附加到xml的问题,php,html,xml,Php,Html,Xml,我正在尝试使用PHP中的SimpleXML对现有的XML文档进行简单的追加。我有一个HTML表单,它调用一个PHP脚本,试图将数据附加到同一目录中已经存在的XML文档中 我已经尝试了这方面的基本实现,但我一直遇到以下错误: Warning: SimpleXMLElement::addChild(): Cannot add child. Parent is not a permanent member of the XML tree in /the/directory/to/the/site/

我正在尝试使用
PHP
中的
SimpleXML
对现有的
XML
文档进行简单的追加。我有一个
HTML
表单,它调用一个
PHP
脚本,试图将数据附加到同一目录中已经存在的
XML
文档中

我已经尝试了这方面的基本实现,但我一直遇到以下错误:

Warning: SimpleXMLElement::addChild(): Cannot add child. Parent is 
not a permanent member of the XML tree in 
/the/directory/to/the/site/generate.php on line 
9

Fatal error: Uncaught Error: Call to a member function addChild() on 
null...
下面是正在使用的已存在的
XML
文件:

<?xml version="1.0" encoding="UTF-8"?>
<tasks>
  <users/>
  <taskList>
    <tasks id="1234">
      <activities>
        <activity/>
      </activities>
    </task>
  </taskList>
</tasks>
我硬编码这些值只是为了让append生效,但最终这些值将来自提交的
html
表单


关于为什么失败有什么想法吗?

您的代码有几个问题。首先,XML无效,关闭标记应该是

当您尝试输入
标记时

$activities = $xml->activities;
这是试图在文档根目录下找到标记,您可以使用完整路径

$activities = $xml->taskList->tasks->activities;
或者使用(我在这段代码中有)XPath来查找它,这还允许您根据id选择(如果必要)您使用的
标记

$activities = $xml->xpath("//activities")[0];

$activity = $activities->addChild('activity');
$activity->addAttribute('id', '45678');
$activity->addChild('assigned', 'Jon');
$activity->addChild('priority', 'low');
您还可以使用不存在的
setAttribute()
,正如代码所示,它是
addAttribute()

$activities = $xml->xpath("//activities")[0];

$activity = $activities->addChild('activity');
$activity->addAttribute('id', '45678');
$activity->addChild('assigned', 'Jon');
$activity->addChild('priority', 'low');