Posted by: prajapatinilesh | September 14, 2007

XML parser

<?
class XMLParser
{
var $parser;
var $filePath;
var $stringVal;
var $document;
var $currTag;
var $tagStack;
function XMLParser($val,$typeVal = ‘file’) {
$this->parser = xml_parser_create();
$this->filePath = null;
$this->stringVal = null;
if ($typeVal == ‘string’) {
$this->stringVal = $val;
}
else {
$this->filePath = $val; //$path
}
$this->document = array();
$this->currTag =& $this->document;
$this->tagStack = array();
}
function parse() {
xml_set_object($this->parser, $this);
xml_set_character_data_handler($this->parser, ‘dataHandler’);
xml_set_element_handler($this->parser, ‘startHandler’, ‘endHandler’);
if ($this->filePath) {
if(!($fp = fopen($this->filePath, “r”))) {
die(“Cannot open XML data file: $this->filePath”);
return false;
}
while($data = fread($fp, 4096)) {
if(!xml_parse($this->parser, $data, feof($fp))) {
die(sprintf(“XML error: %s at line %d”,
xml_error_string(xml_get_error_code($this->parser)),
xml_get_current_line_number($this->parser)));
}
}

fclose($fp);
}
else {
$data = trim($this->stringVal);
if(!xml_parse($this->parser, $data)) {
die(sprintf(“XML error: %s at line %d”,
xml_error_string(xml_get_error_code($this->parser)),
xml_get_current_line_number($this->parser)));
}
}
xml_parser_free($this->parser);
return true;
}
function startHandler($parser, $name, $attribs) {
if(!isset($this->currTag[$name]))
$this->currTag[$name] = array();
$newTag = array();
if(!empty($attribs))
$newTag[‘attr’] = $attribs;
array_push($this->currTag[$name], $newTag);
$t =& $this->currTag[$name];
$this->currTag =& $t[count($t)-1];
array_push($this->tagStack, $name);
}
function dataHandler($parser, $data) {
$data = trim($data);
//if(!empty($data))
//if($data != ”) //because if 0 value than also need to allow
if(!empty($data) || $data == “0”) {
if(isset($this->currTag[‘data’]))
$this->currTag[‘data’] .= $data;
else
$this->currTag[‘data’] = $data;
}
}
function endHandler($parser, $name) {
$this->currTag =& $this->document;
array_pop($this->tagStack);
for($i = 0; $i < count($this->tagStack); $i++) {
$t =& $this->currTag[$this->tagStack[$i]];
$this->currTag =& $t[count($t)-1];
}
}
}
//************
//how to use
//$xmlFilePath = ‘xmlFileCode1.xml’;
//$val = $xmlFilePath;
//$typeVal = ‘file’;

$typeVal = ‘string’;
$val = ‘Whole String of xml here.. if you donot have file…’;

$p =& new XMLParser($val,$typeVal);
$p->parse();

$resultArr = $p->document;
/*echo “<pre>”;
print_r($resultArr);
echo “</pre>”;*/
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: