note 58460 deleted from ref.xml by bjori
| From: | bjori@php.net | Date: | Mon, 09 Oct 2006 11:11:34 +0000 |
| Subject: | note 58460 deleted from ref.xml by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-118278@lists.php.net to get a copy of this message | ||
Note Submitter: alex at whitewhale dot net
----
A simple XML parser that accepts an array which maps tags to the HTML format used for output of
their values. You can optionally specify an array of PHP functions to pass the value through before
it is returned in the specified format:
<?php
class XParser {
protected $parser=NULL;
protected $current='';
public function __construct($xml, $tag_map) {
$this->parser=xml_parser_create();
xml_set_element_handler($this->parser, array($this, 'begin'), array($this,
'end'));
xml_set_character_data_handler($this->parser, array($this, 'cdata'));
$this->tag_map=$tag_map;
if (!xml_parse($this->parser, $xml)) die(sprintf('XML error: %s at line %d',
xml_error_string(xml_get_error_code($this->parser)),
xml_get_current_line_number($this->parser)));
}
protected function begin($parser, $name, $attrs) {
$this->current=$this->current.'/'.$name;
}
protected function cdata($parser, $cdata) {
if (isset($this->tag_map[$this->current][1])) foreach($this->tag_map[$this->current][1]
as $func) $cdata=call_user_func($func, $cdata);
$this->html.=sprintf($this->tag_map[$this->current][0], $cdata);
}
protected function end($parser, $name) {
$this->current=str_replace('/'.$name.'$', '',
$this->current.'$');
}
public function html() {
return $this->html;
}
}
$source='
<books>
<book>
<title>My Book</title>
<description>A good book.</description>
</book>
<book>
<title>Some Other Book</title>
<description>Also a good book.</description>
</book>
</books>
';
$xml=new XParser($source, array(
'/BOOKS/BOOK/TITLE'=>array(
"<b>Title:</b> %s<br>\n", array('strtoupper')
),
'/BOOKS/BOOK/DESCRIPTION'=>array(
"<b>Description:</b> %s<br><br>\n\n"
),
));
echo $xml->html;
?>
Returns:
<b>Title:</b> MY BOOK<br>
<b>Description:</b> A good book.<br><br>
<b>Title:</b> SOME OTHER BOOK<br>
<b>Description:</b> Also a good book.<br><br>