Cep Posted December 20, 2006 Share Posted December 20, 2006 Hello,I am trying to get to grips with how to simply read an xml file and output the contents into php variables. It sounds simple but its beginning to give me a headache. One of the code examples here at phpfreaks is supposedly a class which will read an xml file and output the information into an array.However the original writer has not actually explained how you extract an array from the object he has created with this class.As I don't use classes often could someone please explain how I can use this script to get at the array it has supposedly created?[code=php:0]<?php/** * ArrayFromXML * * @author Pawel Gasiorowski * @copyright Copyright (c) 2005 * @access public **/class ArrayFromXML{ var $parser; var $iter = 0; var $path = array(); var $xml = array(); /** * ArrayFromXML::ArrayFromXML() * * @param string $XML * @return **/ function ArrayFromXML($XML) { $this->parser = xml_parser_create(); xml_set_object($this->parser, &$this); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_set_element_handler($this->parser, "hanleTagStart", "hanleTagEnd"); xml_set_character_data_handler($this->parser, "hanleTagCData"); xml_parse($this->parser, $XML); xml_parser_free($this->parser); $this->xml = $this->xml['_children'][0]; } /** * ArrayFromXML::getEvalPath() * * @return **/ function getEvalPath() { return '$this->xml[' . "'" . implode("']['", $this->path) . "'" . ']'; } /** * ArrayFromXML::hanleTagStart() * * @param object $parser * @param string $tag * @param array $attributes * @return **/ function hanleTagStart($parser, $tag, $attributes) { array_push($this->path, '_children'); array_push($this->path, ($this->iter++)); $e = $this->getEvalPath(); eval ($e . "['_name'] = \$tag;"); if ($attributes !== array()) { eval ($e . "['_attributes'] = \$attributes;"); } } /** * ArrayFromXML::hanleTagCData() * * @param object $parser * @param string $cdata * @return **/ function hanleTagCData($parser, $cdata) { $e = $this->getEvalPath(); eval ($e . "['_value'] = \$cdata;"); } /** * ArrayFromXML::hanleTagEnd() * * @param object $parser * @param string $cdata * @return **/ function hanleTagEnd($parser, $tag) { array_pop($this->path); array_pop($this->path); } } ?>[/code]The usage handler is, [code=php:0]$arr = new ArrayFromXML(file_get_contents('data.xml')); [/code] Link to comment https://forums.phpfreaks.com/topic/31371-xml-script-get-array-from-object/ Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.