Jason February 2016

Generate two XML files using PHP

I currently use the following PHP code to generate an XML file from form inputs on a HTML page (I'm using $_POST):

$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$doc->loadXML($xml->asXML(), LIBXML_NOBLANKS);
$doc->save('../application/'.$filefname.$filesname.'_'.date("Y-m-d").'.xml');

However I would like to generate two XML files, each with different information. Do I need to do something like have two variables? eg. $xml1 and $xml2, $doc1 and $doc2 like so?

$doc1 = new DOMDocument('1.0');
$doc1->formatOutput = true;
$doc1->preserveWhiteSpace = true;
$doc1->loadXML($xml1->asXML(), LIBXML_NOBLANKS);
$doc1->save('../application/'.$filefname.$filesname.'_'.date("Y-m-d").'.xml');

$doc2 = new DOMDocument('1.0');
$doc2->formatOutput = true;
$doc2->preserveWhiteSpace = true;
$doc2->loadXML($xml2->asXML(), LIBXML_NOBLANKS);
$doc2->save('../application/'.$filefname.$filesname.'_'.date("Y-m-d").'.xml');

Eg. Two email addresses and two names are entered into the online form, I want each person's details in a seperate file. Customer 1's name and email in cust1.xml and Customer 2's name and email in cust2.xml

Answers


CodeZombie February 2016

You can reuse the $doc variable. As soon as you assign it a new DOMDocument the $doc variable points to the new instance.

// $doc points to instance #1 of DOMDocument
$doc = new DOMDocument('1.0'); 

...

// $doc points to instance #2 of DOMDocument
$doc = new DOMDocument('1.0');

The same applies to all reference types like objects.

Instead of duplicating your code you should create a function

function createDocument($xml) {
    $doc = new DOMDocument('1.0');
    $doc->formatOutput = true;
    $doc->preserveWhiteSpace = true;
    $doc->loadXML($xml->asXML(), LIBXML_NOBLANKS);
    $doc->save('../application/'.$filefname.$filesname.'_'.date("Y-m-d").'.xml');
}

You should always avoid code duplication. See DRY principle.

Post Status

Asked in February 2016
Viewed 3,687 times
Voted 11
Answered 1 times

Search




Leave an answer