1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
<?
class XMLParser {
var $filename;
var $xml;
var $data;
function XMLParser($xml_file)
{
$this->filename = $xml_file;
$this->xml = xml_parser_create();
xml_set_object($this->xml, $this);
xml_set_element_handler($this->xml, 'startHandler', 'endHandler');
xml_set_character_data_handler($this->xml, 'dataHandler');
$this->parse($xml_file);
}
function parse($xml_file)
{
if (!($fp = fopen($xml_file, 'r'))) {
die('Cannot open XML data file: '.$xml_file);
return false;
}
$bytes_to_parse = 512;
while ($data = fread($fp, $bytes_to_parse)) {
$parse = xml_parse($this->xml, $data, feof($fp));
if (!$parse) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->xml)),
xml_get_current_line_number($this->xml)));
xml_parser_free($this->xml
);
}
}
return true;
}
function startHandler($parser, $name, $attributes)
{
$data['name'] = $name;
if ($attributes) { $data['attributes'] = $attributes; }
$this->data[] = $data;
}
function dataHandler($parser, $data)
{
if($data = trim($data))
{
$index = count($this->data) -1;
if(isset($this->data[$index]['content']))
$this->data[$index]['content'] .= $data;
else $this->data[$index]['content'] = $data;
}
}
function endHandler($parser, $name)
{
if (count($this->data) > 1) {
$data = array_pop($this->data);
$index = count($this->data) - 1;
$this->data[$index]['child'][] = $data;
}
}
function ReturnData ()
{
return $this->data;
}
}
?> |
Partager