[PHP/DOM]remove a XML node itself

We can remove a child node in Dom by php (example from php.nex):

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();

But if you want to delete the node itself, you could do something like this, it will delete the first appearance of the node:

$dom = new DomDocument();
$doc = $dom->loadXML($strXml);
$tagName = $dom->getElementsByTagName('tagName')->item(0);
$tagName->parentNode->removeChild($tagName);
echo $dom->saveXML();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s