I want to save my records from mysql table using PHP to an XML file.I am successfully retrieving records and saving into the database. I want to populate my xml with ALL THE records in my customer table.(CustomerAccountNumber,CustomerAccountName ,AccountBalance, InvAddressLine1)
Here is my code:
<?
$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);
?>
My Question is :
How can I generate customer.xml and how can i save thousand of records in efficient way so that based on the database in THIS FORMAT :
<?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>
I am not getting the clue what I need to do to generate multiple attributes for each record.Kindly help me
You can use 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();
even if it's a XML, it's still a text file, you can just write it with 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);
You might want to consider using SimpleXML, which will help you in you .xml generation. It will be as simple as :
$row->addAttribute("CustomerAccountName", "name");
Documentation here : http://www.php.net/manual/en/simplexml.examples-basic.php