的file_get_contents显示输出意外在读取文件 [英] file_get_contents shows unexpected output while reading a file

查看:233
本文介绍了的file_get_contents显示输出意外在读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要输出内嵌JPG图片为Base64 EN codeD字符串,但是当我这样做:

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."\"/>";

其中, $文件名是为Base64图像本地文本文件。输出如下所示:

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)...." />

和obiously图像不渲染,而是哪里从何而来?它不是在文本文件中。如果去掉,正确显示图像。

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.

推荐答案

这是一个统一code 字节顺序标记。该文件被保存与添加的BOM,表示该文件是EN codeD为UTF-8的编辑器。因此,这些字节其实都是在该文件中,而是一个文本编辑器就不会表现出来,因为它不是文本。为了存储这类数据,你会想删除的BOM。最简单的办法是配置你的编辑器不添加BOM,但如果你没有对文件的创建过程中的影响力,你可以给它的即时在你的脚本也:

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")."\"/>";

这篇关于的file_get_contents显示输出意外在读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆