6

I am trying to use file_put_contents (and file_get_contents for that matter) with a UTF-8 ¥ following this stackoverflow post: How to write file in UTF-8 format? which uses:

$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');

Which wasn't really explained well, since it produces an error of:

mb_convert_encoding(): Illegal character encoding specified

So 'OLD-ENCODING' was just a placeholder they were using. The question I have is what encoding should I change this to? ASCII or ISO-8859-1? What encoding do most web hosts use? Does it matter?

When I open the file, I will get the symbol correctly, only if I have my notepad set with encoding UTF-8. If I open it with another character set it will show up with a "?".

Community
  • 1
  • 1

2 Answers2

4

Try without third parameter.

$str = mb_convert_encoding($str, "UTF-8");

Or auto:

$str = mb_convert_encoding($str, "UTF-8", "auto");

More info and examples on: http://php.net/manual/function.mb-convert-encoding.php

StasGrin
  • 1,800
  • 2
  • 14
  • 30
  • ofc it works. as first programmer rule says: "make it as easy as u can" :) – StasGrin Sep 11 '12 at 22:28
  • I tested it with a lot of different scenarios and it worked each time. thank you, this deserves more upvotes :) –  Sep 11 '12 at 22:37
  • 3
    ty, but u know.. all i did - was reading 2 lines in documentation. try this next time with yourself :) – StasGrin Sep 11 '12 at 22:38
1

mb_convert_encoding($data, 'UTF-8', mb_detect_encoding($data));

mb_detect_encoding

nullpotent
  • 9,162
  • 1
  • 31
  • 42
  • Thanks! but that detects the encoding used on the server? Are my symbols converted to the correct server encoding? –  Sep 11 '12 at 22:20
  • Nope, it detects encoding on `$data` – nullpotent Sep 11 '12 at 22:20
  • oh so that would work for file_get_contents. What about putting it in? what encoding do web servers use? –  Sep 11 '12 at 22:21
  • Well then, you could just simply do `file_put_contents($file, utf8_encode($data));` – nullpotent Sep 11 '12 at 22:24
  • "Encodes an ISO-8859-1 string to UTF-8." That would mean $data which is being used on the website would need to be in ISO format and you would be storing it in UTF-8. That doesn't seem right. I think it would be file_get_contents($file, utf8_encode($data); –  Sep 11 '12 at 22:27
  • That's true. As I said, you could, not should. – nullpotent Sep 11 '12 at 22:31