Konstantin Ippolitov — Senior Backend Engineer

How to fix Yoast SEO sitemap error on line 2 at column 6: XML declaration allowed only at the start of the document in WordPress?

By Konstantin Ippolitov,

Today I had this problem and found an interesting and simple solution on the Internet. You just need to add this script to the index.php file on your website:


<?php
function ___wejns_wp_whitespace_fix($input) {
    $allowed = false;
    $found = false;
    foreach (headers_list() as $header) {
        if (preg_match("/^content-type:\\s+(text\\/|application\\/((xhtml|atom|rss)\\+xml|xml))/i", $header)) {
            $allowed = true;
        }

        if (preg_match("/^content-type:\\s+/i", $header)) {
            $found = true;
        }
    }

    if ($allowed || !$found) {
        return preg_replace("/\\A\\s*/m", "", $input);
    } else {
        return $input;
    }
}
ob_start("___wejns_wp_whitespace_fix");


You can read the original article here.