当我打电话
addChild(' Actor ', '李四');
这个 child 是在最后添加的。有没有办法让这个新 child 成为第一个 child ?
最佳答案
如前所述,SimpleXML 不支持它,因此您必须使用 DOM。这是我的建议:使用您在程序中需要使用的任何内容来扩展 SimpleXMLElement。这样,您可以将所有 DOM 操作和其他 XML 魔法保留在实际程序之外。通过将这两件事分开,您可以提高可读性和可维护性。
以下是使用新方法 prependChild() 扩展 SimpleXMLElement 的方法:
class my_node extends SimpleXMLElement
{
public function prependChild($name, $value)
{
$dom = dom_import_simplexml($this);
$new = $dom->insertBefore(
$dom->ownerDocument->createElement($name, $value),
$dom->firstChild
);
return simplexml_import_dom($new, get_class($this));
}
}
$actors = simplexml_load_string(
'<actors>
<actor>Al Pacino</actor>
<actor>Zsa Zsa Gabor</actor>
</actors>',
'my_node'
);
$actors->addChild('actor', 'John Doe - last');
$actors->prependChild('actor', 'John Doe - first');
die($actors->asXML());
关于php - SimpleXML 如何在节点中添加一个子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2092012/