0

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'        => '[email protected]'),  

                   array('fname'            => 'Josh',
                         'lname'            => 'Jojo',
                         'recipient'        => '[email protected]'),

                   array('fname'            => 'Sam',
                         'lname'            => 'Soso',
                         'recipient'        => '[email protected]'),

                   array('fname'            => 'Dave',
                         'lname'            => 'Dojo',
                         'recipient'        => '[email protected]'));

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,

1
  • Append (.=) your $new to $filecontent instead of setting it (=) and do the fwrite after the foreach-loop Commented Oct 31, 2016 at 10:12

2 Answers 2

1

There are several thinks i believe that can be done better , firstly as Andreas said , you're re assigning the var $new at every loop , so remember a the concat operator dot :

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

and at the end of the loop you will got concatenated all loops iteration on $new .

I suggest you to open document as this :

<?php 

Instead of this :

<?

By this way php will be able to work with XML .

And i suggest to use the specific library to deal with XML instead of the way you're doing.

simpleXml PHP

It's better idea to construct your xml and parse / save intead of working it with disk ... you will face a lot of troubles in future with special chars , charsets ..etc..

Sign up to request clarification or add additional context in comments.

Comments

0

Try this (untested):

<?php

$filename = 'MYDRIVE\XML_TEMPLATE2.xml';
$contents = file_get_contents($filename); 

$emaillist = array(array('fname'            => 'Brad',
                         'lname'            => 'BoBo',
                         'recipient'        => '[email protected]'),  

                   array('fname'            => 'Josh',
                         'lname'            => 'Jojo',
                         'recipient'        => '[email protected]'),

                   array('fname'            => 'Sam',
                         'lname'            => 'Soso',
                         'recipient'        => '[email protected]'),

                   array('fname'            => 'Dave',
                         'lname'            => 'Dojo',
                         'recipient'        => '[email protected]'));

// 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>";

If you have the XML header in your XML_TEMPLATE2.xml, you should remove it there and instead add it to $filecontent before the foreach-loop. Same for the root-node - open it before the foreach and close it after the foreach.

4 Comments

Hi, this gave only one xml file with only the first result
Just checked it that moment - it works as expected. Check, if you have defined $filecontent = '' before the foreach loop.
Hi, yeah and still no luck with this!
Can you show your XML_TEMPLATE2 and the output you get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.