Encoding a string as UTF-8 with BOM in PHP

人盡茶涼 提交于 2019-11-28 19:20:40

Have you tried adding one yourself?

The UTF-8 BOM seems to be 0xEF 0xBB 0xBF, so you can attach it to your string after conversion to UTF-8.

$utf8_with_bom = chr(239) . chr(187) . chr(191) . $utf8_string;

Watch out, though. utf8_encode wants an ISO-8859-1 string. If you're working with XML, make sure that the XML isn't already UTF-8 encoded. The comments on the documentation suggest that the function is broken in a variety of fun ways, so you shouldn't throw it around unless you know that you need it.

Remember, PHP strings are simply dumb, unknowing bytes. They don't have a character set attached to them, so if the data in the string is already UTF-8, you don't need to run the conversion.

Also, the linked Wikipedia article says this:

While Unicode standard allows BOM in UTF-8, it does not require or recommend it. Byte order has no meaning in UTF-8 so a BOM only serves to identify a text stream or file as UTF-8 or that it was converted from another format that has a BOM.

You probably don't need to bother with the BOM tapdance to begin with.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!