Create attribute in existing XML
- by user560411
Hello. I have the following php code that inserts data into XML and works correctly. However, I want to add an ID number like below
<CD id="xxxx">
My question is how can i add an ID into CD for this to work ? I use form to parse the id.
** the main code **
<?php
$CD = array(
'TITLE' => $_POST['title'],
'BAND' => $_POST['band'],
'YEAR' => $_POST['year'],
);
$doc = new DOMDocument();
$doc->load( 'insert.xml' );
$doc->formatOutput = true;
$r = $doc->getElementsByTagName("CATEGORIES")->item(0);
$b = $doc->createElement("CD");
$TITLE = $doc->createElement("TITLE");
$TITLE->appendChild(
$doc->createTextNode( $CD["TITLE"] )
);
$b->appendChild( $TITLE );
$BAND = $doc->createElement("BAND");
$BAND->appendChild(
$doc->createTextNode( $CD["BAND"] )
);
$b->appendChild( $BAND );
$YEAR = $doc->createElement("YEAR");
$YEAR->appendChild(
$doc->createTextNode( $CD["YEAR"] )
);
$b->appendChild( $YEAR );
$r->appendChild( $b );
$doc->save("insert.xml");
?>
the XML file
<?xml version="1.0" encoding="utf-8"?>
<MY_CD>
<CATEGORIES>
<CD>
<TITLE>NEVER MIND THE BOLLOCKS</TITLE>
<BAND>SEX PISTOLS</BAND>
<YEAR>1977</YEAR>
</CD>
<CD>
<TITLE>NEVERMIND</TITLE>
<BAND>NIRVANA</BAND>
<YEAR>1991</YEAR>
</CD>
</CATEGORIES>
</MY_CD>