topical media & game development

talk show tell print

mashup-delicious-06-example6-6.php / php



  <?php
  //this multi-dimensional array will store the XML data
  xml_data_array = array();
  //the XML file to process
  file_name = 'example6-6.xml';
  
  //setup the parser and handlers
  parser = xml_parser_create();
  xml_set_element_handler(parser, "process_start", "process_end");
  xml_set_character_data_handler(parser, "process_cdata");
  
  //open the file
  if (!(file = fopen(file_name, "r")))
     die("could not open the xml file!");
  
  //read from the file, parsing its contents
  while (file_data = fread(file, 5000)) {
     if (!xml_parse(parser, file_data, feof(file)))
         die(xml_error_string(xml_get_error_code(parser)." at line ".xml_get_current_line_number(parser)));
  }
  
  //clear the parser
  xml_parser_free(parser);
  
  //output the raw data array
  echo "<h3>file_name Raw Array Contents:</h3>";
  echo "<pre>";
  print_r(xml_data_array);
  echo "</pre>";
  
  //handle the start of an element
  function process_start(parser, name, attributes)
  {
      global xml_data_array;
      element_data = array("name"=>name,"attributes"=>attributes); 
      array_push(xml_data_array,element_data);
  }
  
  //handle the end of an element
  function process_end(parser, name)
  {
      global xml_data_array;
      xml_data_array[count(xml_data_array)-2]['children'][] = xml_data_array[count(xml_data_array)-1];
      array_pop(xml_data_array);
  }
  
  //handle the character data (content) of an element
  function process_cdata(parser, cdata)
  {
     global xml_data_array,i;
    
     if(trim(cdata))
     {   
         xml_data_array[count(xml_data_array)-1]['cdata']=cdata;   
     }
  }
  ?>
  


(C) Æliens 20/2/2008

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.