2012-11-10 57 views
1

我在更新使用PHP & DOM.My XML文件,我的XML面臨的一個問題是這種格式:保存XML格式正確使用PHP和DOM

原始XML(&所需的XML佈局):

<?xml version="1.0" standalone="yes"?> 
<Rows> 
    <Row CustomerAccountNumber="COU002" /> 
    <Row CustomerAccountNumber="COU023" /> 
    <Row CustomerAccountNumber="C2335" /> 
    <Row CustomerAccountNumber="CvbU002" /> 

而且可以節省即代碼添加新的記錄到XML(customer.xml)是:

<?php 

$xmldoc=new DOMDocument(); 
$xmldoc->load('XML/customer.xml'); 

$newAct= 'c12345'; 

$root = $xmldoc->firstChild; 

$newElement= $xmldoc->createElement('CustomerAccountNumber'); 
$root->appendChild($newElement); 
$newText= $xmldoc->createTextNode($newAct); 
$newElement->appendChild($newText); 

$xmldoc->save('XML/customer.xml'); 
?> 

問題:守則是產生這種格式的新紀錄:

<Rows> 
    <Row CustomerAccountNumber="COU002" /> 
    <Row CustomerAccountNumber="COU023" /> 
    <Row CustomerAccountNumber="C2335" /> 
    <Row CustomerAccountNumber="CvbU002" /> 
    <CustomerAccountNumber>c12345</CustomerAccountNumber> 

</Rows> 

我不明白我在哪裏做mistake.All我要保留我的原始XML format.I希望輸出文件在上面提到的原始格式(請參閱上面)。良好引導我,並指出我在哪裏我犯的錯誤是在文件本身生成不正確的格式。Plz幫助

回答

1

您的問題是,您目前正在創建一個新的CustomerAccountNumber元素。相反,您要創建一個新的元素,然後create a new CustomerAccountNumber attribute

$newElement = $xmldoc->createElement('Row'); 
$newAttribute = $xmldoc->createAttribute('CustomerAccountNumber'); 
$newAttribute->value = $newAct; 
$newElement->appendChild($newAttribute); 
$root->appendChild($newElement);