note 61231 added to ref.xml

From: Date: Sat, 28 Jan 2006 23:45:48 +0000
Subject: note 61231 added to ref.xml
Groups: php.notes 
Request: Send a blank email to php-notes+get-102640@lists.php.net to get a copy of this message
Here's code that will create an associative array from an xml file. Keys are the tag data and subarrays are formed from attributes and child tags <?php $p =& new xmlParser(); $p->parse('/*xml file*/'); print_r($p->output); ?> <?php class xmlParser{ var $xml_obj = null; var $output = array(); var $attrs; function xmlParser(){ $this->xml_obj = xml_parser_create(); xml_set_object($this->xml_obj,$this); xml_set_character_data_handler($this->xml_obj, 'dataHandler'); xml_set_element_handler($this->xml_obj, "startHandler", "endHandler"); } function parse($path){ if (!($fp = fopen($path, "r"))) { die("Cannot open XML data file: $path"); return false; } while ($data = fread($fp, 4096)) { if (!xml_parse($this->xml_obj, $data, feof($fp))) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->xml_obj)), xml_get_current_line_number($this->xml_obj))); xml_parser_free($this->xml_obj); } } return true; } function startHandler($parser, $name, $attribs){ $_content = array(); if(!empty($attribs)) $_content['attrs'] = $attribs; array_push($this->output, $_content); } function dataHandler($parser, $data){ if(!empty($data) && $data!="\n") { $_output_idx = count($this->output) - 1; $this->output[$_output_idx]['content'] .= $data; } } function endHandler($parser, $name){ if(count($this->output) > 1) { $_data = array_pop($this->output); $_output_idx = count($this->output) - 1; $add = array(); if ($_data['attrs']) $add['attrs'] = $_data['attrs']; if ($_data['child']) $add['child'] = $_data['child']; $this->output[$_output_idx]['child'][$_data['content']] = $add; } } } ?> ---- Server IP: 64.246.30.37 Probable Submitter: 67.101.1.229 ---- Manual Page -- http://www.php.net/manual/en/ref.xml.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+61231 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+61231&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+61231&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#102640) next »