PHP批量去除Bom头的方法

检查的代码:

php 复制代码
<?php

$dir = __DIR__;
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

foreach ($files as $file) {
    if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
        $content = file_get_contents($file->getPathname());
        if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
            echo "BOM found in: " . $file->getPathname() . "\n";
        } else {
            echo "No BOM in: " . $file->getPathname() . "\n";
        }
    }
}

批量去除Bom头的代码:

php 复制代码
<?php



$dir = __DIR__; // 当前目录
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

foreach ($files as $file) {
    if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
        echo "Checking: " . $file->getPathname() . "\n"; // 打印正在处理的文件
        $content = file_get_contents($file->getPathname());
        if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
            $content = substr($content, 3);
            file_put_contents($file->getPathname(), $content);
            echo "Removed BOM from: " . $file->getPathname() . "\n";
        }
    }
}

但是最后的方法是:

bash 复制代码
xxd index3.php | head -n 1

发现没有bom头,用PHPStorm右下角的 CR utf-8 改成 CRLF utf-8 就好了。

为什么呢?

CRLF(\r\n):Windows 默认的换行符,两个字符 0x0D 0x0A。

CR(\r):旧版 macOS 使用的换行符,单个 0x0D。

LF(\n):Linux/macOS 默认的换行符,单个 0x0A。

换行格式 符号 ASCII 码 操作系统
LF(换行 Line Feed) \n 0x0A Linux、macOS(新版本)
CR(回车 Carriage Return) \r 0x0D 旧版 macOS(Mac OS 9 及更早)
CRLF(回车+换行) \r\n 0x0D 0x0A Windows
格式 适用系统 影响
CRLF UTF-8 Windows Windows 兼容,Linux 可能会有 ^M 问题
CR UTF-8 旧版 macOS Linux 解析可能出错,现代系统不推荐
LF UTF-8 Linux/macOS 适用于 PHP / Shell / Linux 服务器
相关推荐
m0_738120728 小时前
CTFshow系列——PHP特性Web93-96
开发语言·安全·web安全·php·ctfshow
@CLoudbays_Martin119 小时前
为什么动态视频业务内容不可以被CDN静态缓存?
java·运维·服务器·javascript·网络·python·php
learning_tom11 小时前
HTML图片标签及路径详解
linux·服务器·php
魔道不误砍柴功1 天前
Mac 能够连Wife,但是不能上网问题解决
网络·macos·php
搬码临时工1 天前
怎样让外网计算机访问局域网计算机?通过公网地址访问不同内网服务的设置方法
开发语言·php
Fortinet_CHINA2 天前
案例精述 | 防护即智能 Fortinet赋能英科全栈安全重构实践
安全·重构·php
BingoGo2 天前
PHP Swoole/WebMan/Laravel Octane 等长驻进程框架内存泄露诊断与解决方案
后端·php
站长朋友3 天前
香港主机支持PHP版本吗
开发语言·php·香港主机php版本·php 8.4支持·wordpress主机配置·香港主机性能对比·php版本兼容性测试
腾科张老师3 天前
Telnet 原理与配置
网络·智能路由器·php
lskblog3 天前
使用 PHP Imagick 扩展实现高质量 PDF 转图片功能
android·开发语言·前端·pdf·word·php·laravel