4 * Project: MagpieRSS: a simple RSS integration tool
5 * File: rss_parse.inc - parse an RSS or Atom feed
6 * return as a simple object.
8 * Handles RSS 0.9x, RSS 2.0, RSS 1.0, Atom 0.3, and Atom 1.0
10 * The lastest version of MagpieRSS can be obtained from:
11 * http://magpierss.sourceforge.net
13 * For questions, help, comments, discussion, etc., please join the
14 * Magpie mailing list:
15 * magpierss-general@lists.sourceforge.net
17 * @author Kellan Elliott-McCrea <kellan@protest.net>
24 define('ATOM', 'Atom');
26 require_once (MAGPIE_DIR . 'rss_utils.inc');
29 * Hybrid parser, and object, takes RSS as a string and returns a simple object.
31 * see: rss_fetch.inc for a simpler interface with integrated caching support
37 var $current_item = array(); // item currently being parsed
38 var $items = array(); // collection of parsed items
39 var $channel = array(); // hash of channel fields
40 var $textinput = array();
44 var $encoding = ''; // output encoding of parsed rss
46 var $_source_encoding = ''; // only set if we have to parse xml prolog
51 // define some constants
53 var $_ATOM_CONTENT_CONSTRUCTS = array(
54 'content', 'summary', 'title', /* common */
55 'info', 'tagline', 'copyright', /* Atom 0.3 */
56 'rights', 'subtitle', /* Atom 1.0 */
58 var $_XHTML_CONTENT_CONSTRUCTS = array('body', 'div');
59 var $_KNOWN_ENCODINGS = array('UTF-8', 'US-ASCII', 'ISO-8859-1');
61 // parser variables, useless if you're not a parser, treat as private
62 var $stack = array(); // parser stack
63 var $inchannel = false;
66 var $incontent = array(); // non-empty if in namespaced XML content field
67 var $exclude_top = false; // true when Atom 1.0 type="xhtml"
69 var $intextinput = false;
71 var $current_namespace = false;
74 * Set up XML parser, parse source, and return populated RSS object..
76 * @param string $source string containing the RSS to be parsed
78 * NOTE: Probably a good idea to leave the encoding options alone unless
79 * you know what you're doing as PHP's character set support is
82 * NOTE: A lot of this is unnecessary but harmless with PHP5
85 * @param string $output_encoding output the parsed RSS in this character
86 * set defaults to ISO-8859-1 as this is PHP's
89 * NOTE: might be changed to UTF-8 in future
92 * @param string $input_encoding the character set of the incoming RSS source.
93 * Leave blank and Magpie will try to figure it
97 * @param bool $detect_encoding if false Magpie won't attempt to detect
98 * source encoding. (caveat emptor)
101 function MagpieRSS ($source, $output_encoding='ISO-8859-1',
102 $input_encoding=null, $detect_encoding=true)
104 # if PHP xml isn't compiled in, die
106 if (!function_exists('xml_parser_create')) {
107 $this->error( "Failed to load PHP's XML Extension. " .
108 "http://www.php.net/manual/en/ref.xml.php",
112 list($parser, $source) = $this->create_parser($source,
113 $output_encoding, $input_encoding, $detect_encoding);
116 if (!is_resource($parser)) {
117 $this->error( "Failed to create an instance of PHP's XML parser. " .
118 "http://www.php.net/manual/en/ref.xml.php",
123 $this->parser = $parser;
125 # pass in parser, and a reference to this object
128 xml_set_object( $this->parser, $this );
129 xml_set_element_handler($this->parser,
130 'feed_start_element', 'feed_end_element' );
132 xml_set_character_data_handler( $this->parser, 'feed_cdata' );
134 $status = xml_parse( $this->parser, $source );
136 # try to force convert everything to UTF-8 and parse again
137 # to salvage at least some data from the feed
139 $errorcode = xml_get_error_code( $this->parser );
140 if ( $errorcode != XML_ERROR_NONE ) {
142 xml_parser_free( $this->parser );
144 if (preg_match('/<\?xml.*?encoding="([^ ]+)".*?\?>/',
145 $source, $matches)) {
149 $enc = mb_detect_encoding($string);
152 list($parser, $source) = $this->create_parser($source,
153 $output_encoding, $input_encoding, $detect_encoding);
155 $source = mb_convert_encoding($source, "UTF-8", $enc);
157 $this->parser = $parser;
159 xml_set_object( $this->parser, $this );
160 xml_set_element_handler($this->parser,
161 'feed_start_element', 'feed_end_element' );
163 xml_set_character_data_handler( $this->parser, 'feed_cdata' );
165 $status = xml_parse( $this->parser, $source);
170 $errorcode = xml_get_error_code( $this->parser );
171 if ( $errorcode != XML_ERROR_NONE ) {
172 $xml_error = xml_error_string( $errorcode );
173 $error_line = xml_get_current_line_number($this->parser);
174 $error_col = xml_get_current_column_number($this->parser);
175 $errormsg = "$xml_error at line $error_line, column $error_col";
177 $this->error( $errormsg );
181 xml_parser_free( $this->parser );
186 function feed_start_element($p, $element, &$attrs) {
187 $el = $element = strtolower($element);
188 $attrs = array_change_key_case($attrs, CASE_LOWER);
190 // check for a namespace, and split if found
191 // Don't munge content tags
192 if ( empty($this->incontent) ) {
194 if ( strpos( $element, ':' ) ) {
195 list($ns, $el) = split( ':', $element, 2);
197 if ( $ns and $ns != 'rdf' ) {
198 $this->current_namespace = $ns;
202 # if feed type isn't set, then this is first element of feed
203 # identify feed from root element
205 if (!isset($this->feed_type) ) {
206 if ( $el == 'rdf' ) {
207 $this->feed_type = RSS;
208 $this->feed_version = '1.0';
210 elseif ( $el == 'rss' ) {
211 $this->feed_type = RSS;
212 $this->feed_version = $attrs['version'];
214 elseif ( $el == 'feed' ) {
215 $this->feed_type = ATOM;
216 if ($attrs['xmlns'] == 'http://www.w3.org/2005/Atom') { // Atom 1.0
217 $this->feed_version = '1.0';
219 else { // Atom 0.3, probably.
220 $this->feed_version = $attrs['version'];
222 $this->inchannel = true;
227 // if we're inside a namespaced content construct, treat tags as text
228 if ( !empty($this->incontent) )
230 if ((count($this->incontent) > 1) or !$this->exclude_top) {
231 // if tags are inlined, then flatten
232 $attrs_str = join(' ',
233 array_map('map_attrs',
235 array_values($attrs) )
238 if (strlen($attrs_str) > 0) { $attrs_str = ' '.$attrs_str; }
240 $this->append_content( "<{$element}{$attrs_str}>" );
242 array_push($this->incontent, $el); // stack for parsing content XML
245 elseif ( $el == 'channel' ) {
246 $this->inchannel = true;
249 elseif ($el == 'item' or $el == 'entry' )
251 $this->initem = true;
252 if ( isset($attrs['rdf:about']) ) {
253 $this->current_item['about'] = $attrs['rdf:about'];
257 // if we're in the default namespace of an RSS feed,
258 // record textinput or image fields
260 $this->feed_type == RSS and
261 $this->current_namespace == '' and
264 $this->intextinput = true;
268 $this->feed_type == RSS and
269 $this->current_namespace == '' and
272 $this->inimage = true;
275 // set stack[0] to current element
277 // Atom support many links per containing element.
278 // Magpie treats link elements of type rel='alternate'
279 // as being equivalent to RSS's simple link element.
282 if ($this->feed_type == ATOM and $el == 'link') {
284 if (isset($attrs['rel']) and $attrs['rel'] != 'alternate') {
285 $el = $el . "_" . $attrs['rel']; // pseudo-element names for Atom link elements
288 # handle atom content constructs
289 elseif ( $this->feed_type == ATOM and in_array($el, $this->_ATOM_CONTENT_CONSTRUCTS) )
291 // avoid clashing w/ RSS mod_content
292 if ($el == 'content' ) {
293 $el = 'atom_content';
296 // assume that everything accepts namespaced XML
297 // (that will pass through some non-validating feeds;
298 // but so what? this isn't a validating parser)
299 $this->incontent = array();
300 array_push($this->incontent, $el); // start a stack
302 if ( isset($attrs['type']) and trim(strtolower($attrs['type']))=='xhtml') {
303 $this->exclude_top = true;
305 $this->exclude_top = false;
308 # Handle inline XHTML body elements --CWJ
309 elseif (($this->current_namespace=='xhtml' or
310 (isset($attrs['xmlns']) and $attrs['xmlns'] == 'http://www.w3.org/1999/xhtml'))
311 and in_array($el, $this->_XHTML_CONTENT_CONSTRUCTS) )
313 $this->current_namespace = 'xhtml';
314 $this->incontent = array();
315 array_push($this->incontent, $el); // start a stack
316 $this->exclude_top = false;
319 array_unshift($this->stack, $el);
320 $elpath = join('_', array_reverse($this->stack));
322 $n = $this->element_count($elpath);
323 $this->element_count($elpath, $n+1);
326 array_shift($this->stack);
327 array_unshift($this->stack, $el.'#'.($n+1));
328 $elpath = join('_', array_reverse($this->stack));
331 // this makes the baby Jesus cry, but we can't do it in normalize()
332 // because we've made the element name for Atom links unpredictable
333 // by tacking on the relation to the end. -CWJ
334 if ($atom_link and isset($attrs['href'])) {
335 $this->append($elpath, $attrs['href']);
339 if (count($attrs) > 0) {
340 $this->append($elpath.'@', join(',', array_keys($attrs)));
341 foreach ($attrs as $attr => $value) {
342 $this->append($elpath.'@'.$attr, $value);
350 function feed_cdata ($p, $text) {
352 if ($this->incontent) {
353 $this->append_content( $text );
356 $current_el = join('_', array_reverse($this->stack));
357 $this->append($current_el, $text);
361 function feed_end_element ($p, $el) {
362 $el = strtolower($el);
364 if ( $this->incontent ) {
365 $opener = array_pop($this->incontent);
367 // Don't get bamboozled by namespace voodoo
368 if (strpos($el, ':')) { list($ns, $closer) = split(':', $el); }
369 else { $ns = false; $closer = $el; }
371 // Don't get bamboozled by our munging of <atom:content>, either
372 if ($this->feed_type == ATOM and $closer == 'content') {
373 $closer = 'atom_content';
376 // balance tags properly
377 // note: i don't think this is actually neccessary
378 if ($opener != $closer) {
379 array_push($this->incontent, $opener);
380 $this->append_content("<$el />");
381 } elseif ($this->incontent) { // are we in the content construct still?
382 if ((count($this->incontent) > 1) or !$this->exclude_top) {
383 $this->append_content("</$el>");
385 } else { // shift the opening of the content construct off the normal stack
386 array_shift( $this->stack );
389 elseif ( $el == 'item' or $el == 'entry' )
391 $this->items[] = $this->current_item;
392 $this->current_item = array();
393 $this->initem = false;
395 $this->current_category = 0;
397 elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' )
399 $this->intextinput = false;
401 elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' )
403 $this->inimage = false;
405 elseif ($el == 'channel' or $el == 'feed' )
407 $this->inchannel = false;
410 array_shift( $this->stack );
413 if ( !$this->incontent ) { // Don't munge the namespace after finishing with elements in namespaced content constructs -CWJ
414 $this->current_namespace = false;
418 function concat (&$str1, $str2="") {
419 if (!isset($str1) ) {
425 function append_content($text) {
426 if ( $this->initem ) {
427 if ($this->current_namespace) {
428 $this->concat( $this->current_item[$this->current_namespace][ reset($this->incontent) ], $text );
430 $this->concat( $this->current_item[ reset($this->incontent) ], $text );
433 elseif ( $this->inchannel ) {
434 if ($this->current_namespace) {
435 $this->concat( $this->channel[$this->current_namespace][ reset($this->incontent) ], $text );
437 $this->concat( $this->channel[ reset($this->incontent) ], $text );
442 // smart append - field and namespace aware
443 function append($el, $text) {
447 if ( $this->current_namespace )
449 if ( $this->initem ) {
451 $this->current_item[ $this->current_namespace ][ $el ], $text);
453 elseif ($this->inchannel) {
455 $this->channel[ $this->current_namespace][ $el ], $text );
457 elseif ($this->intextinput) {
459 $this->textinput[ $this->current_namespace][ $el ], $text );
461 elseif ($this->inimage) {
463 $this->image[ $this->current_namespace ][ $el ], $text );
467 if ( $this->initem ) {
469 $this->current_item[ $el ], $text);
471 elseif ($this->intextinput) {
473 $this->textinput[ $el ], $text );
475 elseif ($this->inimage) {
477 $this->image[ $el ], $text );
479 elseif ($this->inchannel) {
481 $this->channel[ $el ], $text );
487 // smart count - field and namespace aware
488 function element_count ($el, $set = NULL) {
492 if ( $this->current_namespace )
494 if ( $this->initem ) {
495 if (!is_null($set)) { $this->current_item[ $this->current_namespace ][ $el.'#' ] = $set; }
496 $ret = (isset($this->current_item[ $this->current_namespace ][ $el.'#' ]) ?
497 $this->current_item[ $this->current_namespace ][ $el.'#' ] : 0);
499 elseif ($this->inchannel) {
500 if (!is_null($set)) { $this->channel[ $this->current_namespace ][ $el.'#' ] = $set; }
501 $ret = (isset($this->channel[ $this->current_namespace][ $el.'#' ]) ?
502 $this->channel[ $this->current_namespace][ $el.'#' ] : 0);
506 if ( $this->initem ) {
507 if (!is_null($set)) { $this->current_item[ $el.'#' ] = $set; }
508 $ret = (isset($this->current_item[ $el.'#' ]) ?
509 $this->current_item[ $el.'#' ] : 0);
511 elseif ($this->inchannel) {
512 if (!is_null($set)) {$this->channel[ $el.'#' ] = $set; }
513 $ret = (isset($this->channel[ $el.'#' ]) ?
514 $this->channel[ $el.'#' ] : 0);
520 function normalize_enclosure (&$source, $from, &$dest, $to, $i) {
521 $id_from = $this->element_id($from, $i);
522 $id_to = $this->element_id($to, $i);
523 if (isset($source["{$id_from}@"])) {
524 foreach (explode(',', $source["{$id_from}@"]) as $attr) {
525 if ($from=='link_enclosure' and $attr=='href') { // from Atom
526 $dest["{$id_to}@url"] = $source["{$id_from}@{$attr}"];
527 $dest["{$id_to}"] = $source["{$id_from}@{$attr}"];
529 elseif ($from=='enclosure' and $attr=='url') { // from RSS
530 $dest["{$id_to}@href"] = $source["{$id_from}@{$attr}"];
531 $dest["{$id_to}"] = $source["{$id_from}@{$attr}"];
534 $dest["{$id_to}@{$attr}"] = $source["{$id_from}@{$attr}"];
540 function normalize_atom_person (&$source, $person, &$dest, $to, $i) {
541 $id = $this->element_id($person, $i);
542 $id_to = $this->element_id($to, $i);
544 // Atom 0.3 <=> Atom 1.0
545 if ($this->feed_version >= 1.0) { $used = 'uri'; $norm = 'url'; }
546 else { $used = 'url'; $norm = 'uri'; }
548 if (isset($source["{$id}_{$used}"])) {
549 $dest["{$id_to}_{$norm}"] = $source["{$id}_{$used}"];
552 // Atom to RSS 2.0 and Dublin Core
553 // RSS 2.0 person strings should be valid e-mail addresses if possible.
554 if (isset($source["{$id}_email"])) {
555 $rss_author = $source["{$id}_email"];
557 if (isset($source["{$id}_name"])) {
558 $rss_author = $source["{$id}_name"]
559 . (isset($rss_author) ? " <$rss_author>" : '');
561 if (isset($rss_author)) {
562 $source[$id] = $rss_author; // goes to top-level author or contributor
563 $dest[$id_to] = $rss_author; // goes to dc:creator or dc:contributor
567 // Normalize Atom 1.0 and RSS 2.0 categories to Dublin Core...
568 function normalize_category (&$source, $from, &$dest, $to, $i) {
569 $cat_id = $this->element_id($from, $i);
570 $dc_id = $this->element_id($to, $i);
572 // first normalize category elements: Atom 1.0 <=> RSS 2.0
573 if ( isset($source["{$cat_id}@term"]) ) { // category identifier
574 $source[$cat_id] = $source["{$cat_id}@term"];
575 } elseif ( $this->feed_type == RSS ) {
576 $source["{$cat_id}@term"] = $source[$cat_id];
579 if ( isset($source["{$cat_id}@scheme"]) ) { // URI to taxonomy
580 $source["{$cat_id}@domain"] = $source["{$cat_id}@scheme"];
581 } elseif ( isset($source["{$cat_id}@domain"]) ) {
582 $source["{$cat_id}@scheme"] = $source["{$cat_id}@domain"];
585 // Now put the identifier into dc:subject
586 $dest[$dc_id] = $source[$cat_id];
590 function normalize_dc_subject (&$source, $from, &$dest, $to, $i) {
591 $dc_id = $this->element_id($from, $i);
592 $cat_id = $this->element_id($to, $i);
594 $dest[$cat_id] = $source[$dc_id]; // RSS 2.0
595 $dest["{$cat_id}@term"] = $source[$dc_id]; // Atom 1.0
598 // simplify the logic for normalize(). Makes sure that count of elements and
599 // each of multiple elements is normalized properly. If you need to mess
600 // with things like attributes or change formats or the like, pass it a
601 // callback to handle each element.
602 function normalize_element (&$source, $from, &$dest, $to, $via = NULL) {
603 if (isset($source[$from]) or isset($source["{$from}#"])) {
604 if (isset($source["{$from}#"])) {
605 $n = $source["{$from}#"];
606 $dest["{$to}#"] = $source["{$from}#"];
610 for ($i = 1; $i <= $n; $i++) {
611 if (isset($via)) { // custom callback for ninja attacks
612 $this->{$via}($source, $from, $dest, $to, $i);
614 else { // just make it the same
615 $from_id = $this->element_id($from, $i);
616 $to_id = $this->element_id($to, $i);
617 $dest[$to_id] = $source[$from_id];
623 function normalize () {
624 // if atom populate rss fields and normalize 0.3 and 1.0 feeds
625 if ( $this->is_atom() ) {
626 // Atom 1.0 elements <=> Atom 0.3 elements (Thanks, o brilliant wordsmiths of the Atom 1.0 standard!)
627 if ($this->feed_version < 1.0) {
628 $this->normalize_element($this->channel, 'tagline', $this->channel, 'subtitle');
629 $this->normalize_element($this->channel, 'copyright', $this->channel, 'rights');
630 $this->normalize_element($this->channel, 'modified', $this->channel, 'updated');
632 $this->normalize_element($this->channel, 'subtitle', $this->channel, 'tagline');
633 $this->normalize_element($this->channel, 'rights', $this->channel, 'copyright');
634 $this->normalize_element($this->channel, 'updated', $this->channel, 'modified');
636 $this->normalize_element($this->channel, 'author', $this->channel['dc'], 'creator', 'normalize_atom_person');
637 $this->normalize_element($this->channel, 'contributor', $this->channel['dc'], 'contributor', 'normalize_atom_person');
639 // Atom elements to RSS elements
640 $this->normalize_element($this->channel, 'subtitle', $this->channel, 'description');
642 if ( isset($this->channel['logo']) ) {
643 $this->normalize_element($this->channel, 'logo', $this->image, 'url');
644 $this->normalize_element($this->channel, 'link', $this->image, 'link');
645 $this->normalize_element($this->channel, 'title', $this->image, 'title');
648 for ( $i = 0; $i < count($this->items); $i++) {
649 $item = $this->items[$i];
651 // Atom 1.0 elements <=> Atom 0.3 elements
652 if ($this->feed_version < 1.0) {
653 $this->normalize_element($item, 'modified', $item, 'updated');
654 $this->normalize_element($item, 'issued', $item, 'published');
656 $this->normalize_element($item, 'updated', $item, 'modified');
657 $this->normalize_element($item, 'published', $item, 'issued');
660 // "If an atom:entry element does not contain
661 // atom:author elements, then the atom:author elements
662 // of the contained atom:source element are considered
663 // to apply. In an Atom Feed Document, the atom:author
664 // elements of the containing atom:feed element are
665 // considered to apply to the entry if there are no
666 // atom:author elements in the locations described
667 // above." <http://atompub.org/2005/08/17/draft-ietf-atompub-format-11.html#rfc.section.4.2.1>
668 if (!isset($item["author#"])) {
669 if (isset($item["source_author#"])) { // from aggregation source
671 $author = "source_author";
672 } elseif (isset($this->channel["author#"])) { // from containing feed
673 $source = $this->channel;
677 $item["author#"] = $source["{$author}#"];
678 for ($au = 1; $au <= $item["author#"]; $au++) {
679 $id_to = $this->element_id('author', $au);
680 $id_from = $this->element_id($author, $au);
682 $item[$id_to] = $source[$id_from];
683 foreach (array('name', 'email', 'uri', 'url') as $what) {
684 if (isset($source["{$id_from}_{$what}"])) {
685 $item["{$id_to}_{$what}"] = $source["{$id_from}_{$what}"];
691 // Atom elements to RSS elements
692 $this->normalize_element($item, 'author', $item['dc'], 'creator', 'normalize_atom_person');
693 $this->normalize_element($item, 'contributor', $item['dc'], 'contributor', 'normalize_atom_person');
694 $this->normalize_element($item, 'summary', $item, 'description');
695 $this->normalize_element($item, 'atom_content', $item['content'], 'encoded');
696 $this->normalize_element($item, 'link_enclosure', $item, 'enclosure', 'normalize_enclosure');
699 if ( isset($item['category#']) ) { // Atom 1.0 categories to dc:subject and RSS 2.0 categories
700 $this->normalize_element($item, 'category', $item['dc'], 'subject', 'normalize_category');
702 elseif ( isset($item['dc']['subject#']) ) { // dc:subject to Atom 1.0 and RSS 2.0 categories
703 $this->normalize_element($item['dc'], 'subject', $item, 'category', 'normalize_dc_subject');
706 // Normalized item timestamp
707 $atom_date = (isset($item['published']) ) ? $item['published'] : $item['updated'];
709 $epoch = @parse_w3cdtf($atom_date);
710 if ($epoch and $epoch > 0) {
711 $item['date_timestamp'] = $epoch;
715 $this->items[$i] = $item;
718 elseif ( $this->is_rss() ) {
719 // RSS elements to Atom elements
720 $this->normalize_element($this->channel, 'description', $this->channel, 'tagline'); // Atom 0.3
721 $this->normalize_element($this->channel, 'description', $this->channel, 'subtitle'); // Atom 1.0 (yay wordsmithing!)
722 $this->normalize_element($this->image, 'url', $this->channel, 'logo');
724 for ( $i = 0; $i < count($this->items); $i++) {
725 $item = $this->items[$i];
727 // RSS elements to Atom elements
728 $this->normalize_element($item, 'description', $item, 'summary');
729 $this->normalize_element($item['content'], 'encoded', $item, 'atom_content');
730 $this->normalize_element($item, 'enclosure', $item, 'link_enclosure', 'normalize_enclosure');
733 if ( isset($item['category#']) ) { // RSS 2.0 categories to dc:subject and Atom 1.0 categories
734 $this->normalize_element($item, 'category', $item['dc'], 'subject', 'normalize_category');
736 elseif ( isset($item['dc']['subject#']) ) { // dc:subject to Atom 1.0 and RSS 2.0 categories
737 $this->normalize_element($item['dc'], 'subject', $item, 'category', 'normalize_dc_subject');
740 // Normalized item timestamp
741 if ( $this->is_rss() == '1.0' and isset($item['dc']['date']) ) {
742 $epoch = @parse_w3cdtf($item['dc']['date']);
743 if ($epoch and $epoch > 0) {
744 $item['date_timestamp'] = $epoch;
747 elseif ( isset($item['pubdate']) ) {
748 $epoch = @strtotime($item['pubdate']);
750 $item['date_timestamp'] = $epoch;
754 $this->items[$i] = $item;
761 if ( $this->feed_type == RSS ) {
762 return $this->feed_version;
770 if ( $this->feed_type == ATOM ) {
771 return $this->feed_version;
779 * return XML parser, and possibly re-encoded source
782 function create_parser($source, $out_enc, $in_enc, $detect) {
783 if ( substr(phpversion(),0,1) == 5) {
784 $parser = $this->php5_create_parser($in_enc, $detect);
787 list($parser, $source) = $this->php4_create_parser($source, $in_enc, $detect);
790 $this->encoding = $out_enc;
791 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc);
794 return array($parser, $source);
798 * Instantiate an XML parser under PHP5
800 * PHP5 will do a fine job of detecting input encoding
801 * if passed an empty string as the encoding.
806 function php5_create_parser($in_enc, $detect) {
807 // by default php5 does a fine job of detecting input encodings
808 if(!$detect && $in_enc) {
809 return xml_parser_create($in_enc);
812 return xml_parser_create('');
817 * Instaniate an XML parser under PHP4
819 * Unfortunately PHP4's support for character encodings
820 * and especially XML and character encodings sucks. As
821 * long as the documents you parse only contain characters
822 * from the ISO-8859-1 character set (a superset of ASCII,
823 * and a subset of UTF-8) you're fine. However once you
824 * step out of that comfy little world things get mad, bad,
825 * and dangerous to know.
827 * The following code is based on SJM's work with FoF
828 * @see http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
831 function php4_create_parser($source, $in_enc, $detect) {
833 return array(xml_parser_create($in_enc), $source);
837 if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $source, $m)) {
838 $in_enc = strtoupper($m[1]);
839 $this->source_encoding = $in_enc;
846 if ($this->known_encoding($in_enc)) {
847 return array(xml_parser_create($in_enc), $source);
850 // the dectected encoding is not one of the simple encodings PHP knows
852 // attempt to use the iconv extension to
853 // cast the XML to a known encoding
854 // @see http://php.net/iconv
856 if (function_exists('iconv')) {
857 $encoded_source = iconv($in_enc,'UTF-8', $source);
858 if ($encoded_source) {
859 return array(xml_parser_create('UTF-8'), $encoded_source);
863 // iconv didn't work, try mb_convert_encoding
864 // @see http://php.net/mbstring
865 if(function_exists('mb_convert_encoding')) {
866 $encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc );
867 if ($encoded_source) {
868 return array(xml_parser_create('UTF-8'), $encoded_source);
873 $this->error("Feed is in an unsupported character encoding. ($in_enc) " .
874 "You may see strange artifacts, and mangled characters.",
877 return array(xml_parser_create(), $source);
880 function known_encoding($enc) {
881 $enc = strtoupper($enc);
882 if ( in_array($enc, $this->_KNOWN_ENCODINGS) ) {
890 function error ($errormsg, $lvl=E_USER_WARNING) {
891 // append PHP's error message if track_errors enabled
892 if ( isset($php_errormsg) ) {
893 $errormsg .= " ($php_errormsg)";
895 if ( MAGPIE_DEBUG ) {
896 trigger_error( $errormsg, $lvl);
899 error_log( $errormsg, 0);
902 $notices = E_USER_NOTICE|E_NOTICE;
903 if ( $lvl&$notices ) {
904 $this->WARNING = $errormsg;
906 $this->ERROR = $errormsg;
910 // magic ID function for multiple elemenets.
911 // can be called as static MagpieRSS::element_id()
912 function element_id ($el, $counter) {
913 return $el . (($counter > 1) ? '#'.$counter : '');
917 function map_attrs($k, $v) {
921 // patch to support medieval versions of PHP4.1.x,
922 // courtesy, Ryan Currie, ryan@digibliss.com
924 if (!function_exists('array_change_key_case')) {
925 define("CASE_UPPER",1);
926 define("CASE_LOWER",0);
929 function array_change_key_case($array,$case=CASE_LOWER) {
930 if ($case==CASE_LOWER) $cmd='strtolower';
931 elseif ($case==CASE_UPPER) $cmd='strtoupper';
932 foreach($array as $key=>$value) {
933 $output[$cmd($key)]=$value;