Hi,
I need to parse an xml file and get the element values. I am using this code. I am getting all the elements and their values. However, I am not able to get an attribute - UserID. Please help me with this code to fetch the UserID attribute.
<?php
$file = "samp1.xml";
$depth = array();
$map_array = array("UserId","CourseNum","CourseTitle","LessonNum","LessonTitle","LessonTopic","EventTypeId","TimeOfEvent","PostalCode");
function startElement($parser, $name, $attrs)
{
global $depth;
global $map_array;
for ($i = 0; $i <= $depth[$parser]; $i++) {
echo " ";
}
echo "$name";
echo " : ";
$depth[$parser]++;
}
function endElement($parser, $name)
{
global $depth;
global $map_array;
$depth[$parser]--;
}
function characterData($parser, $data)
{
echo $data;
}
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}
while ($data = fread($fp, 4096))
{
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)));
}
}
xml_parser_free($xml_parser);
?>
XML File
<Report ReportVersion='1.0'>
<SiteId>143</SiteId>
<Scribble>scrib123abc</Scribble>
<TimeOfReport>1087898060</TimeOfReport>
<EventList>
<Event UserId='1234'>
<CourseNum>1</CourseNum>
<CourseTitle>Discover Bible Guides</CourseTitle>
<LessonNum>1</LessonNum>
<LessonTitle>We Can Believe In God</LessonTitle>
<LessonTopic>State of the Life</LessonTopic>
<EventTypeId>1</EventTypeId>
<TimeOfEvent>1087468326</TimeOfEvent>
<PostalCode></PostalCode>
</Event>
</EventList>
</Report>
Thanks
Mahesh