为相同的XML文档编写PHP,而不是为每次迭代创建一个


Write PHP to same XML document, rather than create one for each iteration

我正在编写一些PHP代码,读取XML模板并用PHP数组中的数据替换模板中的一些值。当前,当代码执行时,它将为每次循环迭代输出一个文件,每个文件都替换了正确的值。

我面临的问题是试图将每个输出都放到同一个XML文档中,而不是每个输出一个。以下是截至目前的代码;

<?
$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>";
}
?>

当执行上面的代码时,将创建4个XML文档,并为每条数据记录正确替换变量。

我面临的问题是试图将所有数据放入一个XML文件中。如果有人能就此提出任何建议,我将不胜感激。

一如既往的感谢,

有几个认为我相信可以做得更好,首先正如Andreas所说,你在每个循环中重新分配var $new,所以记住concat操作符。

$new .= str_replace($find,$replace,$contents);

,在循环结束时,你会得到$new上所有循环迭代的连接。

我建议你这样打开文档:

<?php 

而不是:

<?

通过这种方式,php将能够处理XML。

我建议使用特定的库来处理XML,而不是像你这样做。

simpleXml PHP

这是更好的主意构造你的xml和解析/保存,而不是与磁盘工作…

试试这个(未测试):

<?php
$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'));
// This will open/ create the file if non-existent.
$handle      = fopen("MYDRIVE/tempname.xml", "w+");
$filename    = 'MYDRIVE/tempname.xml';
$filecontent = '';
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);
    $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");
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>";

如果你有XML头在你的XML_TEMPLATE2.xml,你应该删除它,而不是把它添加到$filecontent 之前 foreach -循环。根节点也一样——在foreach 之前打开,在foreach之后关闭