// data file
$file = "recipe.xml";
/*
hash of tag names mapped to HTML markup
"RECIPE" => start a new block
"NAME" => in bold
"INGREDIENTS" => unordered list
"DESC" => list items
"PROCESS" => ordered list
"STEP" => list items
*/
$startTags = array(
"RECIPE" => "
",
"NAME" => "",
"DATE" => "(",
"AUTHOR" => "",
"SERVINGS" => "Serves ",
"INGREDIENTS" => "Ingredients:
",
"DESC" => "- ",
"QUANTITY" => "(",
"PROCESS" => "
Preparation:
",
"STEP" => "- "
);
// close tags opened above
$endTags = array(
"NAME" => "
",
"DATE" => ")",
"AUTHOR" => "",
"INGREDIENTS" => "",
"QUANTITY" => ")",
"SERVINGS" => "",
"PROCESS" => "",
);
function startElement($parser, $name, $attrs) {
global $startTags;
// if tag exists as key, print value
if ($startTags[$name]) { echo $startTags[$name]; }
}
function endElement($parser, $name) {
global $endTags;
if ($endTags[$name]) { echo $endTags[$name]; }
}
// process data between tags
function characterData($parser, $data) {
echo $data;
}
// initialize parser
$xml_parser = xml_parser_create();
// set callback functions
xml_set_element_handler($xml_parser, "startElement",
"endElement");
xml_set_character_data_handler($xml_parser, "characterData");
// open XML file
if (!($fp = fopen($file, "r")))
{
die("Cannot locate XML data file: $file");
}
// read and parse data
while ($data = fread($fp, 4096))
{
// error handler
if (!xml_parse($xml_parser, $data, feof($fp)))
{
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
// clean up
xml_parser_free($xml_parser);
?>