<html>
<head><title>Parsing With Expat and PHP</title></head>
<body>
<?php
$cdata = '';
function start_elem ($parser, $name, $attrs) {
switch ($name) {
case ("personal"):
print ("<p>"); break;
case ("name"):
print ("<b><big>"); break;
case ("address"):
print ("<p><b>Address</b>\n"); break;
case ("tel"):
print ("<p><b>Telephone</b>\n"); break;
case ("contact"):
case ("name"):
case ("first"):
case ("middle"):
case ("last"):
case ("title"):
case ("employer"):
case ("dob"):
break;
default:
print ("<b>Warning: Unknown tag '$name'"); break;
}
}
function end_elem ($parser, $name) {
global $cdata;
$cdata = trim ($cdata);
switch ($name)
{
case ("personal"):
print ("</p>\n\n"); break;
case ("name"):
print ("</big></b>\n"); break;
case ("first"):
print ($cdata . " "); $cdata = ""; break;
case ("middle"):
print ($cdata . " "); $cdata = ""; break;
case ("last"):
print ("$cdata"); $cdata = ""; break;
case ("title"):
print ("<br />Title: $cdata\n"); $cdata = ""; break;
case ("employer"):
print ("<br />Company: $cdata\n"); $cdata = ""; break;
case ("dob"):
print ("<br />Birthdate: $cdata\n"); $cdata = ""; break;
default:
print ("Warning: Unknown element '$name'"); break;
}
}
function cdata ($parser, $data) {
global $cdata;
$cdata .= $data;
}
$file = "contact.xml";
$parser = xml_parser_create ();
xml_parser_set_option ($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler ($parser, "start_elem", "end_elem");
xml_set_character_data_handler ($parser, "cdata");
$fp = fopen ($file, "r");
if (!$fp){
die ("Couldn't open $file for reading");
}
while ($xml_input = fread ($fp, 2048)) {
$ok = xml_parse ($parser, $xml_input, feof ($fp));
if (!$ok)
die (sprintf ("Error in $file: '%s' at line %d",
xml_error_string (xml_get_error_code ($parser)),
xml_get_current_line_number ($parser)));
}
xml_parser_free ($parser);
?>
</body>
</html>
/*
<contact id="43956">
<personal>
<name>
<first>J</first>
<middle>J</middle>
<last>J</last>
</name>
<title>Manager</title>
<employer>National Company</employer>
<dob>1951-02-02</dob>
</personal>
</contact>
*/
|