Sitemap error on line 2 at column 6 XML declaration allowed only at the start of the document

Bài viết hôm nay mình sẽ hướng dẫn bạn cách xử lý lỗi error on line 2 at column 6: XML declaration allowed only at the start of the document khi truy cập vào Sitemap được tạo bằng Plugin Yoast SEO hoặc Rank Math.

Khi mình truy cập vào link https://my-domain/sitemap_index.xml thì gặp lỗi như ảnh sau. Và nguyên nhân đó chính là trong việc tạo sitemaps của website. Website đang gặp phải các lỗi trống hay khoảng trắng tại vị trí các dòng và cột tương ứng như thống báo. Vì thế, việc tạo sitemaps sẽ diễn ra sự cố và từ đó website sẽ hiện ra cho chúng ta một thông báo lỗi.

Sitemap error on line 2 at column 6 XML declaration allowed only at the start of the document

Bước 1: Truy cập vào host và tạo file sau

Bạn tạo mới một file có tên là whitespacefix.php hoặc đặt tên bất kỳ cũng được. Sau khi tạo file bạn nhập vào nội dung sau vào file

<?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");
?>

Bước 2: Include vào index.php

Bạn hãy mở file index.php và nhập vào dòng sau bên dưới đoạn <?php

include('whitespacefix.php');
CleanShot 2021 12 28 at 12.36.56@2x

Bây giờ bạn hãy ra trình duyệt vào truy cập vào https://my-domain/include('whitespacefix.php');. Sau đó truy cập lại Sitemap để nhận được kết quả mới.

CleanShot 2021 12 28 at 12.35.39@2x

Chúc bạn thực hiện thành công.

4.8/5 - (5 bình chọn)
Bài viết liên quan