加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – SimpleXML如何在节点中添加一个子节点?

发布时间:2020-12-13 17:35:45 所属栏目:PHP教程 来源:网络整理
导读:当我打电话 addChild(‘actor’,’John Doe’); 这个孩子在最后添加.有没有办法让这个新孩子成为第一个孩子? 正如已经提到的那样,Simple XML不支持,所以你必须使用DOM.这是我建议的:扩展SimpleXMLElement与您需要在程序中使用的任何东西.这样,您可以将所有
当我打电话

addChild(‘actor’,’John Doe’);

这个孩子在最后添加.有没有办法让这个新孩子成为第一个孩子?

正如已经提到的那样,Simple XML不支持,所以你必须使用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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读