Search code examples
phpandroidjsonutf-8encode

utf8_encode does not encode special characters ě/š/č/ř/ž/ý/á, etc


I have the following problem which seems to have no solution and I am absolutely disgusted.

I have Android application where users can upload file to my server and then they can access them. So if user opens his account, this application uses function scandir() and on my server I use method json_encode() to send data to my app to shows him his files and folders. And here is the problem:

If some user for example uploads file with special characters (Válcování stupHovitých vzorko za tepla.pptx) and this file is not utf-8 encoded, then I can't pass it via json_encode, because I get UTF-8 error. So I tried to use method uf8_encode() on each file name and it worked, BUT if there is some file or folder with special characters like č/š/ě/ř/ž/á/ý/í/é, etc. and use method utf8_encode() on it then I get some mess in my application and instead of getting folder with name č, I get name Ä.

I tried nearly everything from htmlspecialchars() to iconv(), but I can't find a method which returns me files and folders on my server with proper names.


Solution

  • Yes, it does not. The doc reads:

    utf8_encode — Encodes an ISO-8859-1 string to UTF-8

    Not sure what encoding it is, but it's definitely not ISO-8859-1.

    You need to use mb-convert-encoding to convert between arbitrary encodings. E.g.

    $utfStr = mb-convert-encoding('č/š/ě/ř/ž/á/ý/í/é', 'UTF-8', 'ISO-8859-15')
    

    If you don't know client's encoding, you may need to use mb_detect_encoding, which may not always work, or be exactly accurate.

    To avoid this mess, I would recommend to do it other way round and send utf-encoded file name from your android app, rather than convert it serverside.