PHP4 XML parser

xmlparser.class.php
<?php
 
class XMLParser {
 
  var $struct = array();
  var $curptr;
  var $parents = array();
 
  function XMLParser($url) {
    $this->curptr =& $this->struct;
    $xmlparser = xml_parser_create();
    xml_parser_set_option($xmlparser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($xmlparser, XML_OPTION_SKIP_WHITE, 1);
    xml_set_object($xmlparser, $this);
    xml_set_element_handler($xmlparser, 'tag_open', 'tag_close');
    xml_set_character_data_handler($xmlparser, 'cdata');
    $fp = @fopen($url, 'r');
 
    while ($data = @fread($fp, 4096))
      xml_parse($xmlparser, $data, feof($fp))
      || die(sprintf("XML error: %s at line %d",
         xml_error_string(xml_get_error_code($xmlparser)),
         xml_get_current_line_number($xmlparser)));
 
    @fclose($fp);
    xml_parser_free($xmlparser);
    $this->struct = $this->struct['children'];
  }
 
  function tag_open($parser, $tag, $attr) {
    $i = @count($this->curptr['children']);
    $j = count($this->parents);
    $this->curptr['children'][$i]=array();
    $this->parents[$j] =& $this->curptr;
    $this->curptr =& $this->curptr['children'][$i];
    $this->curptr['name'] = $tag;
    if (count($attr)>0) $this->curptr['attr'] = $attr;
  }
 
  function tag_close($parser, $tag) {
    $i = count($this->parents);
    if ($i>0) $this->curptr =& $this->parents[$i-1];
    unset($this->parents[$i-1]);
  }
 
  function cdata($parser, $data) {
    $data = trim($data);
    if (empty($this->curptr['value'])) $this->curptr['value'] = '';
    if (!empty($data)) {
      $this->curptr['value'] .= $data;
    }
  }
 
}
 
function getItems($rss, &$result = array()) {
  if (!empty($rss)) {
    foreach ($rss as $i=>$v) {
      if (!empty($v['name']) && $v['name'] == 'item') {
        $result[] = $v['children'];
      } elseif (is_array($v)) {
        getItems($v, $result);
      }
    }
  }
  return $result;
}
 
function findValue($rss, $key, &$result = false) {
  foreach ($rss as $i=>$v) {
    if ($v['name'] == $key) {
      $result = $v['value'];
    } elseif (is_array($v)) {
      findValue($v, $key, $result);
    }
    if ($result !== false) break;
  }
  return $result;
}
 
?>

 
snippets/php/php4xmlparser.txt · Last modified: 2010-01-15 14:40.57 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA