<!-- <contact id="43956"> <personal> <name> <first>J</first> <middle>J</middle> <last>J</last> </name> <title>Manager</title> <employer>National</employer> <dob>1971-12-22</dob> </personal> </contact> -->
<html> <head> <title>Parsing With Expat and PHP</title> </head> <body> <?php $cdata = ''; $cur_elem = ''; $first_name = ''; $middle_name = ''; $last_name = ''; $hdr_row = '<tr><td colspan="2">%s</td></tr>' . "n"; $data_row = '<tr><td >%s</td><td>%s</td></tr>' . "n"; $empty_row = '<tr><td colspan="2"> </td></tr>' . "n"; function start_elem ($parser, $name, $attrs) { global $cur_elem; $cur_elem = $name; if ($name == 'contact') print ("<table cellspacing=0>n"); } function end_elem ($parser, $name) { global $cdata, $cur_elem, $hdr_row, $data_row, $empty_row, $first_name, $last_name, $middle_name; $cdata = trim ($cdata); switch ($name) { case ("contact"): print ("</table>n"); break; case ("personal"): case ("address"): case ("tel"): print ($empty_row); break; case ("name"): print (sprintf ($hdr_row, "$last_name, $first_name $middle_name")); $first_name = $last_name = $middle_name = ''; break; case ("title"): print (sprintf ($data_row, "Title", $cdata)); break; case ("employer"): print (sprintf ($data_row, "Company", $cdata)); break; case ("dob"): print (sprintf ($data_row, "Birthdate", $cdata)); break; } $cdata = ''; } function cdata ($parser, $data) { global $cdata, $cur_elem, $last_name, $first_name, $middle_name; $data = trim ($data); switch ($cur_elem) { case ("first"): $first_name .= $data; break; case ("middle"): $middle_name .= $data; break; case ("last"): $last_name .= $data; break; default: $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>
|