Code Samples: PHP

This example uses a MySQL database to generate the obituaries list, and includes samples of how to sanitize the data. More thorough sanitation or formatting may be needed depending on how the data is stored. Ideally, this file will be regenerated whenever a change is made to the database.


// Define some constants


// Define some functions

// Make the given string safe for XML
function xmlsafe($str) {

	// Do any additional cleaning here: Stripping HTML tags or entities, line breaks, etc.
	// You may also wish to convert your text to UTF-8 here if your DB uses another format.

	// Make the text safe for XML, replacing the apos and trimming it all to clean things up a bit
	$str = trim(str_replace('&#039;','&apos;',htmlspecialchars($str, ENT_QUOTES, 'utf-8')));

	return $str;

} // End function xmlsafe()

// Database connection

$DB = mysql_connect('localhost', 'username', 'password');
mysql_select_db('obituaries_test', $DB);

// Recommended to set the charset to UTF-8
mysql_query('SET NAMES utf8;');
mysql_query('SET CHARACTER SET utf8;');

// Get obituaries and write XML

// ORDER BY makes no real difference here, but you may wish to include
// a WHERE clause to filter out old entries, etc.
$result = mysql_query('SELECT * FROM obituaries');

// Start XML file, including the generation date
$XML = '<?xml version="1.0" encoding="UTF-8"?>
<obituaries generated="'.date('Y-m-d H:i:s').'">

// Build the obituary entries
while ($obit = mysql_fetch_assoc($result)) {

	$XML .=
'	<obit>
		<photo>'.(empty($obit['photo'])? '':xmlsafe(IMAGE_URL.$obit['photo'])).'</photo>

} // End while

// Finish and write the file
$XML .= '</obituaries>';
file_put_contents(XML_FILE, $XML); // Use fopen / fwrite if PHP 4