开始在现有存储库中使用PHP命名空间,所有文件都会出现语法错误

Having replaced the normal <?php with <?php namespace foo; on each file in my main source I received the error:

PHP Fatal error: Namespace declaration statement has to be the very first statement in the script in src/admin_house_videos.php on line 1

On a majority of files. Looking around the internet people suggest that something called UTF8-BOM is to blame, but how can I get rid of this?

It turned out, helpfully, that Sublime Text was able to fix this problem on a per-file basis:

File -> Save with Encoding -> UTF8

However on a large repository this would be time consuming. I then found this guide which suggested that the unix tool awk could be used to replace the file:

awk '{if(NR==1)sub(/^\xef\xbb\xbf/,"");print}' file.php

However trying to write this back to the file with > file.php appended to the end blanked the file, presumably some sort of read/write issue with output is sent to stdout.

So a bash script needed to be written to solve the issue; in my case it was run from a root where the files were in ./src/ but change the $dir parameter to alter this. The echo line is just to report on progress.

#!/bin/bash

dir="./src/"

for file in `find $dir -name "*.php"` ; do
    echo $file
    awk '{if(NR==1)sub(/^\xef\xbb\xbf/,"");print}' $file > $file.awk
    mv $file.awk $file
done