How can I change the name of an XML tag with PHP/SimpleXML?

妖精的绣舞 提交于 2019-12-25 01:26:27

问题


With SimpleXML, it is possible to add/change/delete attributes of a selected Node «on the fly» by typing e.g.

$child->addAttribute('n', $occ_order);

is there a way to alter the name of the $child element as well? I would expect something like

$child->setName('newTagName');

but I cannot find a corresponding function in the API.

Thanks in advance for your hints!


回答1:


From the docs[1] it looks like you can't. And it would be kind of weird if you could too - changing the name makes it a different/new element. What you want to do is delete that element and add a new one in the same place. However whilst there is a addChild method it doesn't look like there is a delete method. So maybe simpleXML is not the right tool here.

Edit: Indeed simpleXML does not provide a delete method. For info on how to do this, please see this answer[2].

1 http://php.net/manual/en/book.simplexml.php

2 Remove a child with a specific attribute, in SimpleXML for PHP




回答2:


You can remove it with unset() if you know exactly where it is i.e. $main->target would be removed as unset($main->target) and add it again with addchild() i.e. $main->addchild(name, value).



来源:https://stackoverflow.com/questions/7414814/how-can-i-change-the-name-of-an-xml-tag-with-php-simplexml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!