Create attribute in XML
Posted
by
user560411
on Stack Overflow
See other posts from Stack Overflow
or by user560411
Published on 2011-01-02T15:51:02Z
Indexed on
2011/01/02
15:53 UTC
Read the original article
Hit count: 312
Hello. I have the following php code that adds data into XML and works correctly. However, in my second step I will create a form that deletes some of the elements. The problem is that I want to add an ID number and then the PHP file will search for it and delete entire node.
My question is how can i add an ID into CD for this to work ?
For example ( <cd id="xxxx"> )
Also, any ideas or examples of a code that deletes CD having the ID would be appreciate.
insert.php ( my index file with the form )
<h1>Playlist</h1>
<form action="insert2.php" method="post">
<fieldset>
<label for="TITLE">TITLE:</label><input type="text" id="title" name="title" /><br />
<label for="title">BAND:</label> <input type="text" id="band" name="band"/><br />
<label for="path">YEAR:</label> <input type="text" id="year" name="year" /> <br />
<input type="submit" />
</fieldset>
</form>
<h2>Current entries:</h2>
<p>TITLE - BAND - YEAR</p>
<?php
$doc = new DOMDocument();
$doc->load( 'insert.xml' );
$CATEGORIES = $doc->getElementsByTagName( "CD" );
foreach( $CATEGORIES as $CD )
{
$TITLES = $CD->getElementsByTagName( "TITLE" );
$TITLE = $TITLES->item(0)->nodeValue;
$BANDS= $CD->getElementsByTagName( "BAND" );
$BAND= $BANDS->item(0)->nodeValue;
$YEARS = $CD->getElementsByTagName( "YEAR" );
$YEAR = $YEARS->item(0)->nodeValue;
echo "<b>$TITLE - $BAND - $YEAR\n</b><br>";
}
?>
inser2.php ( 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