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 服务器
相关推荐
电商API&Tina1 天前
【电商API接口】关于电商数据采集相关行业
java·python·oracle·django·sqlite·json·php
脆皮瞎1 天前
内网横向移动 ?
网络安全·php·内网穿透
用户3074596982071 天前
一文搞懂 PHP 中的 `cURL` 和 `header()`:请求头 vs 响应头
php
百***07451 天前
Step-Audio-2 API 中转调用解决方案:2025 年版
开发语言·php
用户7227868123441 天前
PHP 初学者指南 基础结构与常见错误
php
爱潜水的小L1 天前
自学嵌入式day37,网络编程
开发语言·网络·php
风月歌1 天前
php医院预约挂号系统小程序源代码(源码+文档+数据库)
数据库·微信小程序·小程序·毕业设计·php·源码
计算机学姐1 天前
基于php的非物质文化遗产推广系统
开发语言·vue.js·mysql·tomcat·php·postman
松涛和鸣1 天前
37、UDP网络编程入门
linux·服务器·前端·网络·udp·php
万岳软件开发小城1 天前
在线教育系统源码开发技术解析:课程、直播、考试与多端适配方案
开源·php·在线教育系统源码·教育小程序·教育平台搭建·教育软件开发·在线教育app开发