Jump to content

XML Parsing using expat PHP


alex4099

Recommended Posts

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

  • 2 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.