note 71866 deleted from ref.xml by danbrown
| From: | danbrown@php.net | Date: | Wed, 03 Mar 2010 18:53:43 +0000 |
| Subject: | note 71866 deleted from ref.xml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166615@lists.php.net to get a copy of this message | ||
Note Submitter: dmeekins att gmail doot com
----
I reworked some of the code I found posted previously here, mainly so I could access the structure
of the parsed xml file by the tags' names. So if I was parsing html that's also valid xml,
I could access the page title by
$xmlp->document['HTML'][0]['HEAD'][0]['TITLE'][0]['data'].
The index after the tag name corresponds to the occurrence of that tag. If there were two
<head></head> in the same depth, then the second one could get accessed by
['HEAD'][1].
<?php
class XMLParser
{
var $parser;
var $filePath;
var $document;
var $currTag;
var $tagStack;
function XMLParser($path)
{
$this->parser = xml_parser_create();
$this->filePath = $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(!($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);
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(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];
}
}
}
?>