使用 php 向 xml 文件中的元素添加不同的子元素

add different children to an element in a xml file using php

我想在我的 xml 文件中的元素中添加一些子项,如下所示:

<test>
  <parameter type="double" name="PHONE_NUMBER" />
  <parameter type="string" name="NAME" />
  <parameter type="string" name="E-MAIL" />
  ...
</test>

我试过这样的事情:

$input = simplexml_load_file('new.xml');
$input->test="";
$input->test->addChild("parameter");
$input->test->parameter->addAttribute("type", "double");
$input->test->parameter->addAttribute("name", "PHONE_NUMBER");

$input->test->addChild("parameter");
$input->test->parameter->addAttribute("type", "string");
$input->test->parameter->addAttribute("name", "NAME");
...

但我收到此错误消息:

Warning: SimpleXMLElement::addAttribute() [simplexmlelement.addattribute]: Attribute already exists

如何解决这个问题?

1,您无法访问 xml 根元素,因此请包装您的 xml 例如 '<xml>'.$yourXML.'</xml>

2nd simpleXML 不理解您访问的参数标记。保存点添加child并修改

$str = '<xml><test>
  <parameter type="double" name="PHONE_NUMBER" />
  <parameter type="string" name="NAME" />
  <parameter type="string" name="E-MAIL" />
</test></xml>';

$input = simplexml_load_string($str);
$input->test="";

$child = $input->test->addChild("parameter");
$child->addAttribute("type", "double");
$child->addAttribute("name", "PHONE_NUMBER");

$child = $input->test->addChild("parameter");
$child->addAttribute("type", "string");
$child->addAttribute("name", "NAME");

echo $input->saveXML();