file_get_contents shows unexpected output while reading a file

送分小仙女□ 提交于 2019-12-19 08:29:24

问题


I want to output an inline jpg image as a base64 encoded string, however when I do this :

$contents = file_get_contents($filename);
print "<img src=\"data:image/jpg;base64,".$contents."\"/>";

Where $filename is a local text file with the base64 image. The output is as follows :

<img src="data:image/jpg;base64,/9j/4A..... (the rest of the file)...." />

And obiously the image is not rendered, but where does  come from ? It is not in the text file. If removed, the image is displayed properly.


回答1:


It's a Unicode Byte-Order Mark. The file was saved with an editor that added the BOM to indicate the file is encoded as UTF-8. So those bytes actually are in the file, but a text editor just won't show it since it's not text. For storing this kind of data you'll want to remove the BOM. Easiest way would be to configure your editor not to add the BOM, but if you don't have influence over the creation process of the file you could to it on-the-fly in your script too:

print "<img src=\"data:image/jpeg;base64,".ltrim($contents, "\xEF\xBB\xBF")."\"/>";


来源:https://stackoverflow.com/questions/9720861/file-get-contents-shows-unexpected-output-while-reading-a-file

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