user1914937
user1914937

Reputation: 27

How to delete a node in XML

Why is my code not functioning to delete an element located in my asset.xml

Here is my xml code inside a php file:

<?php

if(isset($_POST["delete"])) {
        $node = $_GET["node"]; //get from form
        $xmldoc->load('asset.xml');
        $y= $xmldoc->getElementsByTagName("asset")[$node];
        $xmldoc.documentElement.removeChild($y);}
?>

my xml file

<?xml version="1.0" encoding="UTF-8"?>
<Assets>
  <asset>
    <AssetType>PROJECTOR</AssetType>
    <Product>DELL</Product>
    <Brand>DELL</Brand>
  </asset>
</Assets>

Upvotes: 1

Views: 122

Answers (2)

Musa
Musa

Reputation: 97672

You'll have to save the file for the changes to persist

$xmldoc->save('asset.xml');

Seeing as the code you posted is actual code

DOMDocument::getElementsByTagName returns a DOMNodeList you'll have to access the elements via DOMNodelist::item

$y = $xmldoc->getElementsByTagName("asset")->item($node);//assuming $node is an integer < # of matched nodes

-> is used to access object properties in php not . so $xmldoc.documentElement.removeChild($y); should be

$xmldoc->documentElement->removeChild($y);

or better yet

$y->parentNode->removeChild($y);

Upvotes: 1

NullPoiиteя
NullPoiиteя

Reputation: 57312

you need to first save file try

$xmldoc->save('asset.xml');

and

The removeChild() method removes a specified node.
The removeAttribute() method removes a specified attribute.

Upvotes: 1

Related Questions