INDEX

PHP - xml file - create - DOM - attribute add

PHP - xml file - create - DOM - attribute add

< ?
$dom = new DomDocument('1.0', 'utf-8');
$books = $dom->appendChild($dom->createElement('books'));
$book = $books->appendChild($dom->createElement('book'));
//-----------------------------------------------------
$book->setAttribute("seq", "1"); //<-- attribute add
//-----------------------------------------------------
$title = $book->appendChild($dom->createElement('title'));
$title->appendChild($dom->createTextNode('This is sample source.'));
$contents = $book->appendChild($dom->createElement('contents'));
$node= dom_import_simplexml($contents);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection('This book is good.'));
$dom->formatOutput = true;
echo $dom->save('test1.xml');
?>

------------------------
(result)
< ?xml version="1.0" encoding="utf-8"?>
< books>
  < book seq="1">
    < title>This is sample source.< /title>
    < contents>< /contents>
  < /book>
< /books>


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