Im trying to parse the following
- <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>
-
<!-- more newsItems with similar structure -->
Im trying to parse EACH newsItem and show
-Article Title (newsTitle)
-Reporter (reporter)
-Date (pubDate)
I CANNOT DO THIS PART BELOW
-# Of ratings (count # of ratings in rating array)
-avg ratings (sum of ratings in array / count )
-max rating ( max / highest rating)
Code is below
- <?php
-
$g_channel = array();
-
$g_elem = null;
-
-
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";
-
-
}
-
-
?>
MUST BE DONE IN EXPAT AND NOT DOM!