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 服务器
相关推荐
执笔论英雄1 小时前
【Deepseek 学网络互联】跨节点通信global 和节点内通信CLAN保序
开发语言·网络·php
?!7142 小时前
Socket网络编程之UDP套件字
linux·网络·c++·网络协议·udp·php
小马过河R1 天前
不加载PHP OpenTelemetry SDK实现Trace‌与Logs
开发语言·分布式·微服务·云原生·php
源码师傅1 天前
PHP+MySQL开发语言 在线下单订水送水小程序源码及搭建指南
php·送水小程序·桶装水小程序·在线下单送水小程序源码·桶装水送货上门小程序·订水线上商城
专注代码七年1 天前
php:5.6-apache Docker镜像中安装 gd mysqli 库 【亲测可用】
php·apache
夕水1 天前
分享一些实用的PHP函数(对比js/ts实现)(1)
后端·php
浩浩测试一下1 天前
reverse_ssh 建立反向 SSH 连接指南 混淆&&AV [好东西哟]
运维·开发语言·网络·安全·网络安全·ssh·php
hl200503301 天前
PHP中的语句
开发语言·php
即安莉2 天前
ESP8266远程控制:实现网络通信与设备控制
开发语言·stm32·单片机·嵌入式硬件·php
吃着火锅x唱着歌2 天前
PHP7内核剖析 学习笔记 第九章 PHP基础语法的实现
笔记·学习·php