0

我想使用 PHP 将 mysql 表中的记录保存到 XML 文件中。我正在成功检索记录并保存到数据库中。我想用我的客户表中的所有记录填充我的 xml。(CustomerAccountNumber,CustomerAccountName ,AccountBalance, InvAddressLine1)

这是我的代码:

<?
  $newAcct=$db_accnt;
$newAcctname=$db_accntname;
$newAcctbalance=$db_accntbalance;

$xmldoc=new DOMDocument();
$xmldoc->load('XML/customer.xml');
$newElement = $xmldoc->createElement('Row');
$newAttribute = $xmldoc->createAttribute('CustomerAccountNumber');
$newAttribute->value = $newAct;
$newElement->appendChild($newAttribute);
$root->appendChild($newElement);
?>

我的问题是:

如何生成 customer.xml 以及如何以有效的方式保存数千条记录,以便基于此格式中的数据库:

  <?xml version="1.0" standalone="yes"?>
  <Rows>
  <Row CustomerAccountNumber="CU002" CustomerAccountName="Customer 1" AccountBalance="289.00" />
  <Row CustomerAccountNumber="5U002" CustomerAccountName="Customer 2" AccountBalance="1899.00" />
   <Row CustomerAccountNumber="CU004" CustomerAccountName="Customer 3" AccountBalance="289.00" />
   <Row CustomerAccountNumber="5U032" CustomerAccountName="Customer 4" AccountBalance="1899.00" />
    </Rows>

我不知道我需要做什么来为每条记录生成多个属性。请帮助我

4

3 回答 3

2

即使它是一个 XML,它仍然是一个文本文件,你可以用file_put_contents().

$xml='<?xml version="1.0" standalone="yes"?>
<Rows>';

while($row=$result->mysqli_fetch_array()){
    $xml.='<Row CustomerAccountNumber="'.$row[0].'" CustomerAccountName="'.$row[1].'" AccountBalance="'.$row[2].'" />';
}
$xml.='</Rows>';
file_put_contents("customer.xml", $xml);
于 2012-11-13T11:14:57.803 回答
2

您可以使用 XMLWriter

$xml =new XMLWriter();
$xml->openURI('file.xml');
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8', 'yes');
$xml->startElement('Rows');
while ( // fetch from DB ) {
  $xml->startElement('Row');
  $xml->writeattribute("CustomerAccountNumber", "1");
  $xml->writeattribute("CustomerAccountName", "2");
  $xml->writeattribute("AccountBalance", "3");
  $xml->endElement();
}
$xml->endElement();
$xml->flush();
于 2012-11-13T11:48:37.687 回答
1

您可能要考虑使用 SimpleXML,它将帮助您生成 .xml。它将很简单:

$row->addAttribute("CustomerAccountName", "name");

此处的文档:http ://www.php.net/manual/en/simplexml.examples-basic.php

于 2012-11-13T11:18:47.390 回答