utf8_decoder.class.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /**
  3. * Convert from Utf8 to another encoding:
  4. *
  5. * - remove BOM
  6. * - change encoding
  7. *
  8. * @copyright (c) 2012 University of Geneva
  9. * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
  10. * @author Laurent Opprecht <laurent@opprecht.info>
  11. */
  12. class Utf8Decoder extends Converter
  13. {
  14. protected $started = false;
  15. protected $to_encoding;
  16. protected $encoding_converter;
  17. function __construct($to_encoding = null)
  18. {
  19. $this->to_encoding = $to_encoding ? $to_encoding : Encoding::system();
  20. $this->encoding_converter = EncodingConverter::create(Utf8::NAME, $this->to_encoding);
  21. $this->reset();
  22. }
  23. function from_encoding()
  24. {
  25. return Utf8::NAME;
  26. }
  27. function to_encoding()
  28. {
  29. return $this->to_encoding;
  30. }
  31. function reset()
  32. {
  33. $this->started = false;
  34. }
  35. function convert($string)
  36. {
  37. if (!$this->started) {
  38. $this->started = true;
  39. $string = Utf8::instance()->trim($string);
  40. return $this->encoding_converter->convert($string);
  41. } else {
  42. return $this->encoding_converter->convert($string);
  43. }
  44. return $string;
  45. }
  46. }