如何在XML文件中添加节点值?

时间:2012-04-10 09:14:57

标签: php xml ajax

$domtree = new DOMDocument('1.0', 'UTF-8');

/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement("xml");
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
//create the  root Envelope
$currentTrack = $domtree->createElement("Envelope");

$currentTrack = $xmlRoot->appendChild($currentTrack);
/* you should enclose the following two lines in a cicle */
//create the first child node
$c=  $currentTrack->appendChild($domtree->createElement('Header'));
$c->appendChild($domtree->createElement('AccountId','04af6cbcfb9f3038281b06389803d577'));

这里我将“version = 2.1”添加到header.how中我添加吗?

1 个答案:

答案 0 :(得分:0)

尝试这样的setAttribute():

    $domtree = new DOMDocument('1.0', 'UTF-8');

    /* create the root element of the xml tree */
    $xmlRoot = $domtree->createElement("xml");
    /* append it to the document created */
    $xmlRoot = $domtree->appendChild($xmlRoot);
    //create the  root Envelope
    $currentTrack = $domtree->createElement("Envelope");

    $currentTrack = $xmlRoot->appendChild($currentTrack);
    /* you should enclose the following two lines in a cicle */
    //create the first child node
    $header = $domtree->createElement('Header');
    $header->setAttribute('version', '2.1');
    $c = $currentTrack->appendChild($header);
    $c->appendChild($domtree->createElement('AccountId', '04af6cbcfb9f3038281b06389803d577'));

    $domtree->save('x.xml');