I'm writing some PHP code that reads an XML template and replaces some values within the template with data from an array in PHP. Currently when the code is executed it will output a file for each iteration of the loop, each which has the correct values replaced.
The problem that I am facing is trying to get each output on to the same XML document, rather than one each. Below is the code as of present;
<?
$filename = 'MYDRIVE\XML_TEMPLATE2.xml';
$contents = file_get_contents($filename);
$emaillist = array(array('fname' => 'Brad',
'lname' => 'BoBo',
'recipient' => 'bbobo@gmail.com'),
array('fname' => 'Josh',
'lname' => 'Jojo',
'recipient' => 'jjojo@gmail.com'),
array('fname' => 'Sam',
'lname' => 'Soso',
'recipient' => 'ssoso@gmail.com'),
array('fname' => 'Dave',
'lname' => 'Dojo',
'recipient' => 'ddojo@hotmail.com'));
foreach ($emaillist as &$person)
{
$fname = $person['fname'];
$lname = $person['lname'];
$recipient = $person['recipient'];
$todaysdate = date("F j, Y, g:i a");
$find = array("[[firstname]]",
"[[lastname]]",
"[[recipient]]",
"[[todaysdate]]");
$replace = array($fname,
$lname,
$recipient,
$todaysdate);
$new = str_replace($find,
$replace,
$contents);
// This will open/ create the file if non-existent.
$handle = fopen("MYDRIVE/tempname.xml", "w+");
$filename = 'MYDRIVE/tempname.xml';
$filecontent = $new;
if (is_writable($filename))
{
print "<b>Data added to file:</b>";
print "<br>";
print "<br>";
if (!$handle = fopen($filename, 'a'))
{
print "Cannot open file ($filename)";
exit;
}
// Adds $filecontent to file.
if (fwrite($handle, $filecontent) === FALSE)
{
print "Cannot write to file ($filename)";
exit;
}
print "Success! <br><br> ($filecontent) <br><br> was added to ($filename)";
fclose($handle);
}
else
{
print "<b>Error:</b>";
print "The file $filename is not writable";
exit();
}
// Generate file name for use.
$filenamegen = date("d_h_i_s") . "_" . $person['recipient'];
if (rename ("MYDRIVE/tempname.xml", "MYDRIVE/" . $filenamegen . ".xml"))
{
print "File successfully saved as : $filenamegen";
print "<br><br>";
}
else
{
print "Error renaming file.";
exit();
}
print "</div>";
}
?>
When The above code is executed, 4 XML documents are created, with the variables correctly replaced for each record of data.
The problem that I am facing is trying to get all of the data in to a single XML file. If anyone could give any advice regarding this it would be much appreciated.
Thanks as always,