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 );
137 $errorcode = xml_get_error_code( $this->parser );
138 if ( $errorcode != XML_ERROR_NONE ) {
139 $xml_error = xml_error_string( $errorcode );
140 $error_line = xml_get_current_line_number($this->parser);
141 $error_col = xml_get_current_column_number($this->parser);
142 $errormsg = "$xml_error at line $error_line, column $error_col";
144 $this->error( $errormsg );
148 xml_parser_free( $this->parser );
153 function feed_start_element($p, $element, &$attrs) {
154 $el = $element = strtolower($element);
155 $attrs = array_change_key_case($attrs, CASE_LOWER);
157 // check for a namespace, and split if found
158 // Don't munge content tags
159 if ( empty($this->incontent) ) {
161 if ( strpos( $element, ':' ) ) {
162 list($ns, $el) = split( ':', $element, 2);
164 if ( $ns and $ns != 'rdf' ) {
165 $this->current_namespace = $ns;
169 # if feed type isn't set, then this is first element of feed
170 # identify feed from root element
172 if (!isset($this->feed_type) ) {
173 if ( $el == 'rdf' ) {
174 $this->feed_type = RSS;
175 $this->feed_version = '1.0';
177 elseif ( $el == 'rss' ) {
178 $this->feed_type = RSS;
179 $this->feed_version = $attrs['version'];
181 elseif ( $el == 'feed' ) {
182 $this->feed_type = ATOM;
183 if ($attrs['xmlns'] == 'http://www.w3.org/2005/Atom') { // Atom 1.0
184 $this->feed_version = '1.0';
186 else { // Atom 0.3, probably.
187 $this->feed_version = $attrs['version'];
189 $this->inchannel = true;
194 // if we're inside a namespaced content construct, treat tags as text
195 if ( !empty($this->incontent) )
197 if ((count($this->incontent) > 1) or !$this->exclude_top) {
198 // if tags are inlined, then flatten
199 $attrs_str = join(' ',
200 array_map('map_attrs',
202 array_values($attrs) )
205 if (strlen($attrs_str) > 0) { $attrs_str = ' '.$attrs_str; }
207 $this->append_content( "<{$element}{$attrs_str}>" );
209 array_push($this->incontent, $el); // stack for parsing content XML
212 elseif ( $el == 'channel' ) {
213 $this->inchannel = true;
216 elseif ($el == 'item' or $el == 'entry' )
218 $this->initem = true;
219 if ( isset($attrs['rdf:about']) ) {
220 $this->current_item['about'] = $attrs['rdf:about'];
224 // if we're in the default namespace of an RSS feed,
225 // record textinput or image fields
227 $this->feed_type == RSS and
228 $this->current_namespace == '' and
231 $this->intextinput = true;
235 $this->feed_type == RSS and
236 $this->current_namespace == '' and
239 $this->inimage = true;
242 // set stack[0] to current element
244 // Atom support many links per containing element.
245 // Magpie treats link elements of type rel='alternate'
246 // as being equivalent to RSS's simple link element.
249 if ($this->feed_type == ATOM and $el == 'link') {
251 if (isset($attrs['rel']) and $attrs['rel'] != 'alternate') {
252 $el = $el . "_" . $attrs['rel']; // pseudo-element names for Atom link elements
255 # handle atom content constructs
256 elseif ( $this->feed_type == ATOM and in_array($el, $this->_ATOM_CONTENT_CONSTRUCTS) )
258 // avoid clashing w/ RSS mod_content
259 if ($el == 'content' ) {
260 $el = 'atom_content';
263 // assume that everything accepts namespaced XML
264 // (that will pass through some non-validating feeds;
265 // but so what? this isn't a validating parser)
266 $this->incontent = array();
267 array_push($this->incontent, $el); // start a stack
269 if ( isset($attrs['type']) and trim(strtolower($attrs['type']))=='xhtml') {
270 $this->exclude_top = true;
272 $this->exclude_top = false;
275 # Handle inline XHTML body elements --CWJ
276 elseif (($this->current_namespace=='xhtml' or
277 (isset($attrs['xmlns']) and $attrs['xmlns'] == 'http://www.w3.org/1999/xhtml'))
278 and in_array($el, $this->_XHTML_CONTENT_CONSTRUCTS) )
280 $this->current_namespace = 'xhtml';
281 $this->incontent = array();
282 array_push($this->incontent, $el); // start a stack
283 $this->exclude_top = false;
286 array_unshift($this->stack, $el);
287 $elpath = join('_', array_reverse($this->stack));
289 $n = $this->element_count($elpath);
290 $this->element_count($elpath, $n+1);
293 array_shift($this->stack);
294 array_unshift($this->stack, $el.'#'.($n+1));
295 $elpath = join('_', array_reverse($this->stack));
298 // this makes the baby Jesus cry, but we can't do it in normalize()
299 // because we've made the element name for Atom links unpredictable
300 // by tacking on the relation to the end. -CWJ
301 if ($atom_link and isset($attrs['href'])) {
302 $this->append($elpath, $attrs['href']);
306 if (count($attrs) > 0) {
307 $this->append($elpath.'@', join(',', array_keys($attrs)));
308 foreach ($attrs as $attr => $value) {
309 $this->append($elpath.'@'.$attr, $value);
317 function feed_cdata ($p, $text) {
319 if ($this->incontent) {
320 $this->append_content( $text );
323 $current_el = join('_', array_reverse($this->stack));
324 $this->append($current_el, $text);
328 function feed_end_element ($p, $el) {
329 $el = strtolower($el);
331 if ( $this->incontent ) {
332 $opener = array_pop($this->incontent);
334 // Don't get bamboozled by namespace voodoo
335 if (strpos($el, ':')) { list($ns, $closer) = split(':', $el); }
336 else { $ns = false; $closer = $el; }
338 // Don't get bamboozled by our munging of <atom:content>, either
339 if ($this->feed_type == ATOM and $closer == 'content') {
340 $closer = 'atom_content';
343 // balance tags properly
344 // note: i don't think this is actually neccessary
345 if ($opener != $closer) {
346 array_push($this->incontent, $opener);
347 $this->append_content("<$el />");
348 } elseif ($this->incontent) { // are we in the content construct still?
349 if ((count($this->incontent) > 1) or !$this->exclude_top) {
350 $this->append_content("</$el>");
352 } else { // shift the opening of the content construct off the normal stack
353 array_shift( $this->stack );
356 elseif ( $el == 'item' or $el == 'entry' )
358 $this->items[] = $this->current_item;
359 $this->current_item = array();
360 $this->initem = false;
362 $this->current_category = 0;
364 elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' )
366 $this->intextinput = false;
368 elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' )
370 $this->inimage = false;
372 elseif ($el == 'channel' or $el == 'feed' )
374 $this->inchannel = false;
377 array_shift( $this->stack );
380 if ( !$this->incontent ) { // Don't munge the namespace after finishing with elements in namespaced content constructs -CWJ
381 $this->current_namespace = false;
385 function concat (&$str1, $str2="") {
386 if (!isset($str1) ) {
392 function append_content($text) {
393 if ( $this->initem ) {
394 if ($this->current_namespace) {
395 $this->concat( $this->current_item[$this->current_namespace][ reset($this->incontent) ], $text );
397 $this->concat( $this->current_item[ reset($this->incontent) ], $text );
400 elseif ( $this->inchannel ) {
401 if ($this->current_namespace) {
402 $this->concat( $this->channel[$this->current_namespace][ reset($this->incontent) ], $text );
404 $this->concat( $this->channel[ reset($this->incontent) ], $text );
409 // smart append - field and namespace aware
410 function append($el, $text) {
414 if ( $this->current_namespace )
416 if ( $this->initem ) {
418 $this->current_item[ $this->current_namespace ][ $el ], $text);
420 elseif ($this->inchannel) {
422 $this->channel[ $this->current_namespace][ $el ], $text );
424 elseif ($this->intextinput) {
426 $this->textinput[ $this->current_namespace][ $el ], $text );
428 elseif ($this->inimage) {
430 $this->image[ $this->current_namespace ][ $el ], $text );
434 if ( $this->initem ) {
436 $this->current_item[ $el ], $text);
438 elseif ($this->intextinput) {
440 $this->textinput[ $el ], $text );
442 elseif ($this->inimage) {
444 $this->image[ $el ], $text );
446 elseif ($this->inchannel) {
448 $this->channel[ $el ], $text );
454 // smart count - field and namespace aware
455 function element_count ($el, $set = NULL) {
459 if ( $this->current_namespace )
461 if ( $this->initem ) {
462 if (!is_null($set)) { $this->current_item[ $this->current_namespace ][ $el.'#' ] = $set; }
463 $ret = (isset($this->current_item[ $this->current_namespace ][ $el.'#' ]) ?
464 $this->current_item[ $this->current_namespace ][ $el.'#' ] : 0);
466 elseif ($this->inchannel) {
467 if (!is_null($set)) { $this->channel[ $this->current_namespace ][ $el.'#' ] = $set; }
468 $ret = (isset($this->channel[ $this->current_namespace][ $el.'#' ]) ?
469 $this->channel[ $this->current_namespace][ $el.'#' ] : 0);
473 if ( $this->initem ) {
474 if (!is_null($set)) { $this->current_item[ $el.'#' ] = $set; }
475 $ret = (isset($this->current_item[ $el.'#' ]) ?
476 $this->current_item[ $el.'#' ] : 0);
478 elseif ($this->inchannel) {
479 if (!is_null($set)) {$this->channel[ $el.'#' ] = $set; }
480 $ret = (isset($this->channel[ $el.'#' ]) ?
481 $this->channel[ $el.'#' ] : 0);
487 function normalize_enclosure (&$source, $from, &$dest, $to, $i) {
488 $id_from = $this->element_id($from, $i);
489 $id_to = $this->element_id($to, $i);
490 if (isset($source["{$id_from}@"])) {
491 foreach (explode(',', $source["{$id_from}@"]) as $attr) {
492 if ($from=='link_enclosure' and $attr=='href') { // from Atom
493 $dest["{$id_to}@url"] = $source["{$id_from}@{$attr}"];
494 $dest["{$id_to}"] = $source["{$id_from}@{$attr}"];
496 elseif ($from=='enclosure' and $attr=='url') { // from RSS
497 $dest["{$id_to}@href"] = $source["{$id_from}@{$attr}"];
498 $dest["{$id_to}"] = $source["{$id_from}@{$attr}"];
501 $dest["{$id_to}@{$attr}"] = $source["{$id_from}@{$attr}"];
507 function normalize_atom_person (&$source, $person, &$dest, $to, $i) {
508 $id = $this->element_id($person, $i);
509 $id_to = $this->element_id($to, $i);
511 // Atom 0.3 <=> Atom 1.0
512 if ($this->feed_version >= 1.0) { $used = 'uri'; $norm = 'url'; }
513 else { $used = 'url'; $norm = 'uri'; }
515 if (isset($source["{$id}_{$used}"])) {
516 $dest["{$id_to}_{$norm}"] = $source["{$id}_{$used}"];
519 // Atom to RSS 2.0 and Dublin Core
520 // RSS 2.0 person strings should be valid e-mail addresses if possible.
521 if (isset($source["{$id}_email"])) {
522 $rss_author = $source["{$id}_email"];
524 if (isset($source["{$id}_name"])) {
525 $rss_author = $source["{$id}_name"]
526 . (isset($rss_author) ? " <$rss_author>" : '');
528 if (isset($rss_author)) {
529 $source[$id] = $rss_author; // goes to top-level author or contributor
530 $dest[$id_to] = $rss_author; // goes to dc:creator or dc:contributor
534 // Normalize Atom 1.0 and RSS 2.0 categories to Dublin Core...
535 function normalize_category (&$source, $from, &$dest, $to, $i) {
536 $cat_id = $this->element_id($from, $i);
537 $dc_id = $this->element_id($to, $i);
539 // first normalize category elements: Atom 1.0 <=> RSS 2.0
540 if ( isset($source["{$cat_id}@term"]) ) { // category identifier
541 $source[$cat_id] = $source["{$cat_id}@term"];
542 } elseif ( $this->feed_type == RSS ) {
543 $source["{$cat_id}@term"] = $source[$cat_id];
546 if ( isset($source["{$cat_id}@scheme"]) ) { // URI to taxonomy
547 $source["{$cat_id}@domain"] = $source["{$cat_id}@scheme"];
548 } elseif ( isset($source["{$cat_id}@domain"]) ) {
549 $source["{$cat_id}@scheme"] = $source["{$cat_id}@domain"];
552 // Now put the identifier into dc:subject
553 $dest[$dc_id] = $source[$cat_id];
557 function normalize_dc_subject (&$source, $from, &$dest, $to, $i) {
558 $dc_id = $this->element_id($from, $i);
559 $cat_id = $this->element_id($to, $i);
561 $dest[$cat_id] = $source[$dc_id]; // RSS 2.0
562 $dest["{$cat_id}@term"] = $source[$dc_id]; // Atom 1.0
565 // simplify the logic for normalize(). Makes sure that count of elements and
566 // each of multiple elements is normalized properly. If you need to mess
567 // with things like attributes or change formats or the like, pass it a
568 // callback to handle each element.
569 function normalize_element (&$source, $from, &$dest, $to, $via = NULL) {
570 if (isset($source[$from]) or isset($source["{$from}#"])) {
571 if (isset($source["{$from}#"])) {
572 $n = $source["{$from}#"];
573 $dest["{$to}#"] = $source["{$from}#"];
577 for ($i = 1; $i <= $n; $i++) {
578 if (isset($via)) { // custom callback for ninja attacks
579 $this->{$via}($source, $from, $dest, $to, $i);
581 else { // just make it the same
582 $from_id = $this->element_id($from, $i);
583 $to_id = $this->element_id($to, $i);
584 $dest[$to_id] = $source[$from_id];
590 function normalize () {
591 // if atom populate rss fields and normalize 0.3 and 1.0 feeds
592 if ( $this->is_atom() ) {
593 // Atom 1.0 elements <=> Atom 0.3 elements (Thanks, o brilliant wordsmiths of the Atom 1.0 standard!)
594 if ($this->feed_version < 1.0) {
595 $this->normalize_element($this->channel, 'tagline', $this->channel, 'subtitle');
596 $this->normalize_element($this->channel, 'copyright', $this->channel, 'rights');
597 $this->normalize_element($this->channel, 'modified', $this->channel, 'updated');
599 $this->normalize_element($this->channel, 'subtitle', $this->channel, 'tagline');
600 $this->normalize_element($this->channel, 'rights', $this->channel, 'copyright');
601 $this->normalize_element($this->channel, 'updated', $this->channel, 'modified');
603 $this->normalize_element($this->channel, 'author', $this->channel['dc'], 'creator', 'normalize_atom_person');
604 $this->normalize_element($this->channel, 'contributor', $this->channel['dc'], 'contributor', 'normalize_atom_person');
606 // Atom elements to RSS elements
607 $this->normalize_element($this->channel, 'subtitle', $this->channel, 'description');
609 if ( isset($this->channel['logo']) ) {
610 $this->normalize_element($this->channel, 'logo', $this->image, 'url');
611 $this->normalize_element($this->channel, 'link', $this->image, 'link');
612 $this->normalize_element($this->channel, 'title', $this->image, 'title');
615 for ( $i = 0; $i < count($this->items); $i++) {
616 $item = $this->items[$i];
618 // Atom 1.0 elements <=> Atom 0.3 elements
619 if ($this->feed_version < 1.0) {
620 $this->normalize_element($item, 'modified', $item, 'updated');
621 $this->normalize_element($item, 'issued', $item, 'published');
623 $this->normalize_element($item, 'updated', $item, 'modified');
624 $this->normalize_element($item, 'published', $item, 'issued');
627 // "If an atom:entry element does not contain
628 // atom:author elements, then the atom:author elements
629 // of the contained atom:source element are considered
630 // to apply. In an Atom Feed Document, the atom:author
631 // elements of the containing atom:feed element are
632 // considered to apply to the entry if there are no
633 // atom:author elements in the locations described
634 // above." <http://atompub.org/2005/08/17/draft-ietf-atompub-format-11.html#rfc.section.4.2.1>
635 if (!isset($item["author#"])) {
636 if (isset($item["source_author#"])) { // from aggregation source
638 $author = "source_author";
639 } elseif (isset($this->channel["author#"])) { // from containing feed
640 $source = $this->channel;
644 $item["author#"] = $source["{$author}#"];
645 for ($au = 1; $au <= $item["author#"]; $au++) {
646 $id_to = $this->element_id('author', $au);
647 $id_from = $this->element_id($author, $au);
649 $item[$id_to] = $source[$id_from];
650 foreach (array('name', 'email', 'uri', 'url') as $what) {
651 if (isset($source["{$id_from}_{$what}"])) {
652 $item["{$id_to}_{$what}"] = $source["{$id_from}_{$what}"];
658 // Atom elements to RSS elements
659 $this->normalize_element($item, 'author', $item['dc'], 'creator', 'normalize_atom_person');
660 $this->normalize_element($item, 'contributor', $item['dc'], 'contributor', 'normalize_atom_person');
661 $this->normalize_element($item, 'summary', $item, 'description');
662 $this->normalize_element($item, 'atom_content', $item['content'], 'encoded');
663 $this->normalize_element($item, 'link_enclosure', $item, 'enclosure', 'normalize_enclosure');
666 if ( isset($item['category#']) ) { // Atom 1.0 categories to dc:subject and RSS 2.0 categories
667 $this->normalize_element($item, 'category', $item['dc'], 'subject', 'normalize_category');
669 elseif ( isset($item['dc']['subject#']) ) { // dc:subject to Atom 1.0 and RSS 2.0 categories
670 $this->normalize_element($item['dc'], 'subject', $item, 'category', 'normalize_dc_subject');
673 // Normalized item timestamp
674 $atom_date = (isset($item['published']) ) ? $item['published'] : $item['updated'];
676 $epoch = @parse_w3cdtf($atom_date);
677 if ($epoch and $epoch > 0) {
678 $item['date_timestamp'] = $epoch;
682 $this->items[$i] = $item;
685 elseif ( $this->is_rss() ) {
686 // RSS elements to Atom elements
687 $this->normalize_element($this->channel, 'description', $this->channel, 'tagline'); // Atom 0.3
688 $this->normalize_element($this->channel, 'description', $this->channel, 'subtitle'); // Atom 1.0 (yay wordsmithing!)
689 $this->normalize_element($this->image, 'url', $this->channel, 'logo');
691 for ( $i = 0; $i < count($this->items); $i++) {
692 $item = $this->items[$i];
694 // RSS elements to Atom elements
695 $this->normalize_element($item, 'description', $item, 'summary');
696 $this->normalize_element($item['content'], 'encoded', $item, 'atom_content');
697 $this->normalize_element($item, 'enclosure', $item, 'link_enclosure', 'normalize_enclosure');
700 if ( isset($item['category#']) ) { // RSS 2.0 categories to dc:subject and Atom 1.0 categories
701 $this->normalize_element($item, 'category', $item['dc'], 'subject', 'normalize_category');
703 elseif ( isset($item['dc']['subject#']) ) { // dc:subject to Atom 1.0 and RSS 2.0 categories
704 $this->normalize_element($item['dc'], 'subject', $item, 'category', 'normalize_dc_subject');
707 // Normalized item timestamp
708 if ( $this->is_rss() == '1.0' and isset($item['dc']['date']) ) {
709 $epoch = @parse_w3cdtf($item['dc']['date']);
710 if ($epoch and $epoch > 0) {
711 $item['date_timestamp'] = $epoch;
714 elseif ( isset($item['pubdate']) ) {
715 $epoch = @strtotime($item['pubdate']);
717 $item['date_timestamp'] = $epoch;
721 $this->items[$i] = $item;
728 if ( $this->feed_type == RSS ) {
729 return $this->feed_version;
737 if ( $this->feed_type == ATOM ) {
738 return $this->feed_version;
746 * return XML parser, and possibly re-encoded source
749 function create_parser($source, $out_enc, $in_enc, $detect) {
750 if ( substr(phpversion(),0,1) == 5) {
751 $parser = $this->php5_create_parser($in_enc, $detect);
754 list($parser, $source) = $this->php4_create_parser($source, $in_enc, $detect);
757 $this->encoding = $out_enc;
758 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc);
761 return array($parser, $source);
765 * Instantiate an XML parser under PHP5
767 * PHP5 will do a fine job of detecting input encoding
768 * if passed an empty string as the encoding.
773 function php5_create_parser($in_enc, $detect) {
774 // by default php5 does a fine job of detecting input encodings
775 if(!$detect && $in_enc) {
776 return xml_parser_create($in_enc);
779 return xml_parser_create('');
784 * Instaniate an XML parser under PHP4
786 * Unfortunately PHP4's support for character encodings
787 * and especially XML and character encodings sucks. As
788 * long as the documents you parse only contain characters
789 * from the ISO-8859-1 character set (a superset of ASCII,
790 * and a subset of UTF-8) you're fine. However once you
791 * step out of that comfy little world things get mad, bad,
792 * and dangerous to know.
794 * The following code is based on SJM's work with FoF
795 * @see http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
798 function php4_create_parser($source, $in_enc, $detect) {
800 return array(xml_parser_create($in_enc), $source);
804 if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $source, $m)) {
805 $in_enc = strtoupper($m[1]);
806 $this->source_encoding = $in_enc;
813 if ($this->known_encoding($in_enc)) {
814 return array(xml_parser_create($in_enc), $source);
817 // the dectected encoding is not one of the simple encodings PHP knows
819 // attempt to use the iconv extension to
820 // cast the XML to a known encoding
821 // @see http://php.net/iconv
823 if (function_exists('iconv')) {
824 $encoded_source = iconv($in_enc,'UTF-8', $source);
825 if ($encoded_source) {
826 return array(xml_parser_create('UTF-8'), $encoded_source);
830 // iconv didn't work, try mb_convert_encoding
831 // @see http://php.net/mbstring
832 if(function_exists('mb_convert_encoding')) {
833 $encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc );
834 if ($encoded_source) {
835 return array(xml_parser_create('UTF-8'), $encoded_source);
840 $this->error("Feed is in an unsupported character encoding. ($in_enc) " .
841 "You may see strange artifacts, and mangled characters.",
844 return array(xml_parser_create(), $source);
847 function known_encoding($enc) {
848 $enc = strtoupper($enc);
849 if ( in_array($enc, $this->_KNOWN_ENCODINGS) ) {
857 function error ($errormsg, $lvl=E_USER_WARNING) {
858 // append PHP's error message if track_errors enabled
859 if ( isset($php_errormsg) ) {
860 $errormsg .= " ($php_errormsg)";
862 if ( MAGPIE_DEBUG ) {
863 trigger_error( $errormsg, $lvl);
866 error_log( $errormsg, 0);
869 $notices = E_USER_NOTICE|E_NOTICE;
870 if ( $lvl&$notices ) {
871 $this->WARNING = $errormsg;
873 $this->ERROR = $errormsg;
877 // magic ID function for multiple elemenets.
878 // can be called as static MagpieRSS::element_id()
879 function element_id ($el, $counter) {
880 return $el . (($counter > 1) ? '#'.$counter : '');
884 function map_attrs($k, $v) {
888 // patch to support medieval versions of PHP4.1.x,
889 // courtesy, Ryan Currie, ryan@digibliss.com
891 if (!function_exists('array_change_key_case')) {
892 define("CASE_UPPER",1);
893 define("CASE_LOWER",0);
896 function array_change_key_case($array,$case=CASE_LOWER) {
897 if ($case==CASE_LOWER) $cmd='strtolower';
898 elseif ($case==CASE_UPPER) $cmd='strtoupper';
899 foreach($array as $key=>$value) {
900 $output[$cmd($key)]=$value;