Create attribute in existing XML

Posted by user560411 on Stack Overflow See other posts from Stack Overflow or by user560411
Published on 2011-01-02T16:52:46Z Indexed on 2011/01/02 16:53 UTC
Read the original article Hit count: 191

Filed under:
|

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>

© Stack Overflow or respective owner

Related posts about php

Related posts about Xml