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.

<?php

/**************************************************/
// Define some constants

define('URL','http://site.com/');
define('IMAGE_URL',URL.'images/obituaries/');
define('DETAIL_URL',URL.'obituaries.php?obitID=');
define('XML_FILE','obituaries.xml');


/**************************************************/
// 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>
		<uniqID>'.xmlsafe($obit['id']).'</uniqID>
		<firstName>'.xmlsafe($obit['firstName']).'</firstName>
		<lastName>'.xmlsafe($obit['lastName']).'</lastName>
		<middleInitial>'.xmlsafe($obit['middleInitial']).'</middleInitial>
		<deathDate>'.xmlsafe($obit['deathDate']).'</deathDate>
		<city>'.xmlsafe($obit['city']).'</city>
		<state>'.xmlsafe($obit['state']).'</state>
		<bio>'.xmlsafe($obit['bio']).'</bio>
		<visitation>'.xmlsafe($obit['visitation']).'</visitation>
		<service>'.xmlsafe($obit['service']).'</service>
		<photo>'.(empty($obit['photo'])? '':xmlsafe(IMAGE_URL.$obit['photo'])).'</photo>
		<link>'.xmlsafe(DETAIL_URL.$obit['id']).'</link>
	</obit>
';

} // End while

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

mysql_close($DB);
?>