Remove a UTF-8 BOM Before Parsing YAML in PHP

A UTF-8 byte-order mark at the start of a YAML file can become part of the first key or interfere with the document marker in parsers that do not strip it. Remove exactly one leading UTF-8 BOM before parsing, without modifying BOM-like bytes elsewhere in the document.

Last updated: November 1, 2026.

<?php
use Symfony\Component\Yaml\Yaml;

$yaml = file_get_contents($path);
if ($yaml === false) {
    throw new RuntimeException('Unable to read the YAML file.');
}

if (str_starts_with($yaml, "")) {
    $yaml = substr($yaml, 3);
}

$config = Yaml::parse($yaml, Yaml::PARSE_EXCEPTION_ON_ALIAS);

The check operates on the three UTF-8 signature bytes and removes them only at offset zero. It does not trim whitespace or delete the Unicode character from quoted YAML values.

Why the first key can look correct but fail

The YAML 1.2 specification treats a leading BOM as an encoding marker rather than content. If a parser exposes it as U+FEFF, a key that appears to be foo may actually contain an invisible leading character, so lookups fail.

Inspect the first bytes with a hex viewer or bin2hex(substr($yaml, 0, 3)). The UTF-8 BOM is efbbbf. Do not use broad character replacement because a BOM code point inside a quoted scalar may be intentional data.

Constrain untrusted configuration input

Symfony documents parsing YAML strings and files and provides limits and flags for untrusted content. Set a reasonable file-size limit before reading uploads, reject aliases when they are unnecessary, catch ParseException, and validate the resulting array against an expected schema.

Prefer saving configuration files as UTF-8 without BOM and update the YAML component when a release includes native handling for your case. Continue with understanding UTF-8 BOM problems, handling invalid encodings in PHP, and fixing invalid UTF-8 in structured data.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov