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 服务器
相关推荐
海尔辛2 小时前
学习黑客 MAC 地址深入了解
学习·macos·php
Q_Q19632884752 小时前
python小说网站管理系统-小说阅读系统
开发语言·spring boot·python·django·flask·node.js·php
2501_906314326 小时前
使用Scrapeless Scraping Browser的自动化和网页抓取最佳实践
搜索引擎·自动化·php
pqq的迷弟7 小时前
redis多路复用IO模型 以及 6.0引入的多线程模型
数据库·redis·php
小马过河R8 小时前
基于OpenTelemetry的分布式链路追踪Trace‌实现(PHP篇)
开发语言·分布式·微服务·云原生·php
徊忆羽菲9 小时前
学习整理使用php将SimpleXMLElement 对象解析成数组格式的方法
开发语言·学习·php
Waitccy10 小时前
HTTP 与 HTTPS 的深度剖析:差异、原理与应用场景
网络协议·http·https·php
YJQ99671 天前
LVS负载均衡群集解析:理解LVS-NAT的工作原理
php·负载均衡·lvs
运维有小邓@1 天前
比较入站和出站防火墙规则
服务器·网络·php
qianqianaao1 天前
实验六 基于Python的数字图像压缩算法
开发语言·图像处理·python·opencv·计算机视觉·自然语言处理·php