INDEX

PHP - xml - DOM - Delete Item

To delete a node of the search attributes.

(xml file : test1.xml)
< ?xml version="1.0" encoding="utf-8"?>
< books>
  < book title="title1">
    < title>This is sample source.
    < contents>This book is good.
  < /book>
  < book title="title2">
    < title>This is sample source.
    < contents>This book is good.
  < /book>
  < book title="title3">
    < title>This is sample source.
    < contents>This book is good.
  < /book>
< /books>

(PHP Code)
$xmlFile = "test1.xml";
$xmlDoc = new DOMDocument();
$xmlDoc->preserveWhiteSpace = false; 
$xmlDoc->formatOutput = true;
$xmlDoc->load($xmlFile);

$xpath = new DOMXPath($xmlDoc);
$result = $xpath->query("//book[@title='title2']")->item(0);
$result->parentNode->removeChild($result);
$xmlDoc->save($xmlFile);

(result : test1.xml)
< ?xml version="1.0" encoding="utf-8"?>
< books>
  < book title="title1">
    < title>This is sample source.
    < contents>This book is good.
  < /book>
  < book title="title3">
    < title>This is sample source.
    < contents>This book is good.
  < /book>
< /books>


Copyright(c) 2007-2020 coding.dojeun.com All Rights Reserved.