在XML中创建属性

时间:2011-01-02 15:51:02

标签: php xml

我有以下PHP代码将数据添加到XML并正常工作。但是,在我的第二步中,我将创建一个删除某些元素的表单。问题是我想添加一个ID号,然后PHP文件将搜索它并删除整个节点。

我的问题是如何在CD中添加ID才能使用?

  For example  ( <cd id="xxxx"> )

insert.php(带表格的索引文件)

<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(主要代码)

<?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");  
?>

XML文件

<?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>

1 个答案:

答案 0 :(得分:4)

$dom = $new_dom = new DOMDocument;
$dom->load('insert.xml');

/* add attribute id */
$xpath = new DOMXpath($dom);
$items = $xpath->query('/MY_CD/CATEGORIES/*');
$id = 1;
foreach ($items as $item)
{
  $item->setAttributeNode(new DOMAttr('id', $id));
  ++$id;
}

/* remove a node where id=2 */
$new_dom->loadXMl($dom->saveXML());
$xpath = new DOMXpath($new_dom);
$items = $xpath->query('/MY_CD/CATEGORIES/CD[@id="2"]');
foreach ($items as $item)
{
  $item->parentNode->removeChild($item);
}
echo $new_dom->saveXML();