I am trying to parse an XML file that looks like the following
snippet:

<latest_news>
        <item id="1">
                <date>12/03/03</date>
                <title>New benefits to members</title>
                <description>
                        <![CDATA[hello :)<BR>Hello ]]>
                </description>
        </item>
</latęst_news>

however it will not parse (doesnt display anything) when I put the
CDATA line on the same line as the description and put the close tag
on the same line as well then all works fine, this is ok in this
exmple but it is of little use when the CDATA contains many lines or
is complicated etc is there a way to solve this? I have attaced the
PHP code I am using below but can not see anything wrong with it ??

Many Thanks
Toby.
<?php
if( ! ($fp = fopen( "./news.xml" , "r" )) )
  die("Couldn't open xml file!");
$counter = 0;
$person_data = array();
$xml_current_tag_state = '';

function startElementHandler( $parser, $element_name, $element_attribs ) {
  global $counter;
  global $person_data;
  global $xml_current_tag_state;
  if( $element_name == "ITEM" ) {
    $person_data[$counter]["id"] = $element_attribs["ID"];
  } else {
    $xml_current_tag_state = $element_name;
  }
}

function endElementHandler( $parser, $element_name ) {
  global $counter;
  global $person_data;
  global $xml_current_tag_state;
  $xml_current_tag_state = '';
  
  if( $element_name == "ITEM" ) {
    $counter++;
  }
}

function characterDataHandler( $parser , $data ) {
  global $counter;
  global $person_data;
  global $xml_current_tag_state;
  if( $xml_current_tag_state == '' )
    return;
  if( $xml_current_tag_state == "DATE" ) {
    $person_data[$counter]["date"] = $data;
  }
  if( $xml_current_tag_state == "TITLE" ) {
    $person_data[$counter]["title"] = $data;
  }
  if( $xml_current_tag_state == "DESCRIPTION" ) {
    $person_data[$counter]["description"] = $data;
  }
}
if( !($xml_parser = xml_parser_create()) )
  die("Couldn't create XML parser!");

xml_set_element_handler($xml_parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler($xml_parser, "characterDataHandler");
while( $data = fread($fp, 4096) )
{
  if( !xml_parse($xml_parser, $data, feof($fp)) )
  {
    break; // get out of while loop if we're done with the file
  }
}
xml_parser_free($xml_parser);
?>

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>
<HEAD>
  <TITLE>Parsing the Sample XML File</TITLE>
</HEAD>

<BODY BGCOLOR="#ffffff">

<?php
for( $i=0 ; $i < $counter ; ++$i ) {
  echo "Date:&nbsp;&nbsp;" . $person_data[$i]["date"] . "<BR>\n";
  echo "Title:&nbsp;&nbsp;" . $person_data[$i]["title"] . "<BR>\n";
  echo "Description:&nbsp;&nbsp;" . $person_data[$i]["description"] . "<BR>\n";
  echo "<BR>\n";
}

?>

</BODY>
</HTML>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to