<?php
/**
 * fromvega XML Generator DB
 *
 * Generates an XML file from records in a database table based on an user XML model.
 *
 * Your XML model must be a well formed XML file with an example of the code that you
 * want to be created for each record. The root tag will be kept and each children of
 * the model will be duplicated for each record.
 *
 * You can also run this script through the command line to interact with the
 * script as it generates the XML files.
 *
 *         Usage: php xmlgen2_db.php
 *
 * If you need to generate an XML from files in a directory please use the other
 * flavor of this script (DIR) found at fromvega.com.
 *
 * @author fromvega
 * @version 1.0
 * @link http://fromvega.com
 */

/**
 * Customize the behavior of the script
 *
 */

// name of the XML file
$xmlFileName 'dbrecords.xml';

// name of the XML model
$xmlModelName 'model_db.xml';

// database configuration - the DNS below is a sample for MySQL
$db_dsn   'mysql:host=localhost;dbname=mydatabase';
$db_user  'username';
$db_pass  'password';

// set the table to be read or build a custom query below
$db_table 'mytable';

// custom query (null select all table data)
$db_query null;


/**
 * Code - Do not modify below this point (unless you know what you're doing)
 *
 */

/**
 * Preparing the XML data
 */

// create DOMDocument from the XML model
$dom DOMDocument::load($xmlModelName);

// get the root element
$doc $dom->documentElement;

// get children
$children  $doc->childNodes;

// start creating a new XML tree
$xmlModel '<xmlgen>';

// copy the model's children as string
foreach ($children as $child) {
    
$xmlModel .= $dom->saveXML($child);
}

// closes the root tag
$xmlModel .= '</xmlgen>';

// remove children
$doc->nodeValue '';

// get the remaining nodes as string
$xmlRootModel $dom->saveXML();


/**
 * Open database connection and select data
 */
try {
    
$dbh = new PDO($db_dsn$db_user$db_pass);

    if(
$db_query != null){
        
$rows $dbh->query($db_query);
    } else {
        
$rows $dbh->query('SELECT * FROM '.$db_table);
    }
} catch (
Exception $e){
    print 
"Error!: " $e->getMessage() . "<br/>";
    die();
}

/**
 * Start looping
 */

// for HTML display purposes
if(PHP_SAPI !== 'cli') echo "<pre>\n";

// informative display
echo "----------------------------------------------\n";
echo 
"  fromvega XML Generator 2.DB - fromvega.com\n";
echo 
"-----------------------------------------------\n";
echo 
"Creating XML file...\n";

// replace placeholders of the root tag
$xmlRootModel str_replace('{tablename}'$db_table$xmlRootModel);
$xmlRootModel preg_replace('/{callback:(\w+?)}/e''call_user_func($1, $db_table, $row)'$xmlRootModel);
$xmlRootModel preg_replace('/{input:(\w+?)}/e''getUserInput($1)'$xmlRootModel);

// recreate the DOM with the new data
$dom->loadXML($xmlRootModel);
$doc $dom->documentElement;

// loop through the results
foreach ($rows as $row) {

    
// make a copy of the model
    
$xmlField $xmlModel;

    
// replace placeholders
    
$xmlField str_replace('{tablename}'$db_table$xmlField);
    
$xmlField preg_replace('/{field:(\w+?)}/e''$row[$1]'$xmlField);
    
$xmlField preg_replace('/{callback:(\w+?)}/e''call_user_func($1, $db_table, $row)'$xmlField);
    
$xmlField preg_replace('/{input:(\w+?)}/e''getUserInput($1)'$xmlField);

    
// load the new data
    
$newDom DOMDocument::loadXML($xmlField);

    
// add each node to the DOMDocument
    
foreach ($newDom->documentElement->childNodes as $child) {
        
$newNode $dom->importNode($childtrue);
        
$doc->appendChild($newNode);
    }
}

// creates the XML file
$dom->save($xmlFileName);

// informative display
echo "Done!\n";
if(
PHP_SAPI !== 'cli') echo '</pre>';

/**
 * Callback and other functions
 */

/**
 * Get the user input from the CLI
 *
 * @param string $desc
 * @return string
 */
function getUserInput($desc){

    
// if cliMode ask for input otherwise leave blank
    
if(PHP_SAPI == 'cli'){
        echo 
"Enter $desc: ";
        return 
trim(fgets(STDIN));
    } else {
        return 
' ';
    }

}

/**
 * Return the date
 *
 * @param string $table
 * @param array $row
 * @return string
 */
function today($table$row){
    return 
date('y/m/d');
}