XML Parsing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Mahesh
Forum Newbie
Posts: 7
Joined: Sat Apr 10, 2004 4:48 am
Location: Coimbatore, India
Contact:

XML Parsing

Post by Mahesh »

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.

Code: Select all

<?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

Code: Select all

&lt;Report ReportVersion='1.0'&gt;
&lt;SiteId&gt;143&lt;/SiteId&gt;
&lt;Scribble&gt;scrib123abc&lt;/Scribble&gt;
&lt;TimeOfReport&gt;1087898060&lt;/TimeOfReport&gt;
&lt;EventList&gt;
&lt;Event UserId='1234'&gt;
&lt;CourseNum&gt;1&lt;/CourseNum&gt;
&lt;CourseTitle&gt;Discover Bible Guides&lt;/CourseTitle&gt;
&lt;LessonNum&gt;1&lt;/LessonNum&gt;
&lt;LessonTitle&gt;We Can Believe In God&lt;/LessonTitle&gt;
&lt;LessonTopic&gt;State of the Life&lt;/LessonTopic&gt;
&lt;EventTypeId&gt;1&lt;/EventTypeId&gt;
&lt;TimeOfEvent&gt;1087468326&lt;/TimeOfEvent&gt;
&lt;PostalCode&gt;&lt;/PostalCode&gt;
&lt;/Event&gt;
&lt;/EventList&gt;
&lt;/Report&gt;
Thanks
Mahesh



feyd | use

Code: Select all

and

Code: Select all

tags; Read : [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in Forums[/url][/color]
Post Reply