【发布时间】:2013-10-29 09:00:24
【问题描述】:
您好,如果不创建新文件并保存,我正在尝试将数据附加到现有文件中。 相反,我的代码将数据保存了一次。下一个数据集只是覆盖第一个。 请帮我弄清楚我做错了什么......
在 cmets 之后,我更改了代码,现在我最终得到了 警告:DOMDocument::load() [domdocument.load]: 文档末尾的额外内容
function toXml($reg)
{
$xmlFile = "customers.xml";
$doc = new DomDocument('1.0');
$doc->load( $xmlFile);
$cusCart = $doc -> createElement('cusCart');
//$cusCart = $doc->appendChild($cusCart);
foreach ($reg as $item => $val )
{
$customer = $doc->createElement('customer');
$customer = $cusCart->appendChild($customer);
$cusId = $doc->createElement('cusId');
$cusId = $customer->appendChild($cusId);
$value = $doc->createTextNode($item);
$value = $cusId->appendChild($value);
$fName = $doc->createElement('fName');
$fName = $customer->appendChild($fName);
$value1 = $doc->createTextNode($val["fName"]);
$value1 = $fName->appendChild($value1);
$lName = $doc->createElement('lName');
$lName = $customer->appendChild($lName);
$value2 = $doc->createTextNode($val["lName"]);
$value2 = $lName->appendChild($value2);
$phone = $doc->createElement('phone');
$phone = $customer->appendChild($phone);
$value3 = $doc->createTextNode($val["phone"]);
$value3 = $phone->appendChild($value3);
$email = $doc->createElement('email');
$email = $customer->appendChild($email);
$value4 = $doc->createTextNode($val["email"]);
$value4 = $email->appendChild($value4);
$pwd = $doc->createElement('pw');
$pwd = $customer->appendChild($pwd);
$value5 = $doc->createTextNode($val["pw"]);
$value5 = $pwd->appendChild($value5);
}
$cusCart = $doc->appendChild($cusCart);
$doc->save($xmlFile);
$strXml = $doc->saveXML();
echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
【问题讨论】:
-
你的 if/else (file_exists('cusXML.xml')) 中的指令都是一样的。为什么要这样做?
-
如果文件不存在,我正在尝试将数据保存到文件中...
-
您的意思是“如果文件不存在,请执行此操作,否则执行完全相同的操作”
-
您需要对将 XML 加载到 DOMDocument 的代码行进行更好的错误处理。先修复那个位置,处理加载失败的情况。