note 56762 deleted from ref.xml by bjori
| From: | bjori@php.net | Date: | Mon, 09 Oct 2006 11:12:25 +0000 |
| Subject: | note 56762 deleted from ref.xml by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-118282@lists.php.net to get a copy of this message | ||
Note Submitter: monte at NOT-SP-AM dot ohrt dot com
----
Here is another simple XML-to-array parser using the expat library. My goal was something that
parsed everything (attributes, data, etc.) cleanly and also encapsulated all of its functionality
inside a PHP class. You can supply anything fopen() accepts (file, url, etc.)
usage:
<?php
$p =& new xmlParser();
$p->parse('http://domain.com/rss.xml');
print_r($p->output);
?>
Here is the source:
<?php
class xmlParser{
var $xml_obj = null;
var $output = array();
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('name' => $name);
if(!empty($attribs))
$_content['attrs'] = $attribs;
array_push($this->output, $_content);
}
function dataHandler($parser, $data){
if(!empty($data)) {
$_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;
$this->output[$_output_idx]['child'][] = $_data;
}
}
}
?>