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 服务器
相关推荐
iblade13 小时前
网络:TCP序列号和滑动窗口,顺序保证
网络·tcp/ip·php
工控小楠15 小时前
CCLink IE转ModbusTCP网关配置无纸记录器(中篇)
服务器·网络·php
失因17 小时前
H3CNE 综合实验二解析与实施指南
运维·开发语言·网络·智能路由器·php
kp0000018 小时前
PHP strip_tags() 函数详解
网络安全·php
ONLYOFFICE19 小时前
如何将 ONLYOFFICE 文档集成到使用 Laravel 框架编写的 PHP 网络应用程序中
php·laravel
计算机毕设定制辅导-无忧学长21 小时前
性能优化实践:Modbus 在高并发场景下的吞吐量提升(二)
网络·性能优化·php
Q_Q19632884751 天前
python的抗洪救灾管理系统
开发语言·spring boot·python·django·flask·node.js·php
VCR__1 天前
VLAN实验
服务器·开发语言·php
星释2 天前
WAMP允许远程访问
php·apache·wamp
用户3074596982072 天前
🧠 PHP 变量从零开始讲明白(小白也能看懂)
后端·php