alex4099 Posted May 14, 2009 Share Posted May 14, 2009 I have the following snippet from my XML file that i need to parse in PHP using expat (NOT DOM!) sports.xml <channel> <newsItem> <newsTitle>U.S. Tops Guatemala 2-0 in Cup Qualifier (AP)</newsTitle> <reporters><reporter>RONALD BLUM</reporter></reporters> <ratings> <rating>3</rating> <rating>2</rating> <rating>2</rating> <rating>5</rating> <rating>3</rating> <rating>5</rating> <rating>3</rating> <rating>4</rating> </ratings> <pubDate>Thu, 31 Mar 2005 03:29:44 GMT</pubDate> </newsItem> ..++ 50+ other newsItems </channel> My PHP code to parse this xml file below shows Title of article Reporter Pub Date I need help calculating AVG RATING MAX RATING # OF RATINGS (for each news article!) <?php $g_channel = array(); $g_elem = null; $Counter = 0; function startElement( $parser, $name, $attrs ) { global $g_channel, $g_elem; if ( $name == 'newsItem' ) $g_channel []= array(); $g_elem = $name; } function endElement( $parser, $name ) { global $g_elem; $g_elem = null; } function textData( $parser, $text ) { global $g_channel, $g_elem; if ( $g_elem == 'REPORTER' || $g_elem == 'PUBDATE' || $g_elem == 'NEWSTITLE' ) { $g_channel[ count( $g_channel ) - 1 ][ $g_elem ] = $text; } } $parser = xml_parser_create(); xml_set_element_handler( $parser, "startElement", "endElement" ); xml_set_character_data_handler( $parser, "textData" ); $f = fopen( 'yahoosports.xml', 'r' ); while( $data = fread( $f, 4096 ) ) { xml_parse( $parser, $data ); } xml_parser_free( $parser ); foreach( $g_channel as $newsItem ) { echo $newsItem['NEWSTITLE']." - ".$newsItem['REPORTER']." - "; echo $newsItem['PUBDATE']."\n"; } ?> anyhelp is greatly appreciated! Link to comment https://forums.phpfreaks.com/topic/158058-xml-parsing-using-expat-php/ Share on other sites More sharing options...
alex4099 Posted May 23, 2009 Author Share Posted May 23, 2009 lol wow Link to comment https://forums.phpfreaks.com/topic/158058-xml-parsing-using-expat-php/#findComment-840464 Share on other sites More sharing options...
RichardRotterdam Posted May 23, 2009 Share Posted May 23, 2009 Is there any reason why you particularly want to use expat over any other php function/class? I'd go for simple_xml Link to comment https://forums.phpfreaks.com/topic/158058-xml-parsing-using-expat-php/#findComment-840620 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.