XML声明仅允许在文档开头处。

7
6个回答

27

这是我找到的解决方案:首先,您需要在WordPress根目录下创建一个名为“whitespacefix.php”的PHP文件,并添加以下内容。

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

然后打开index.php文件,在<?php标记之后添加以下行:

include('whitespacefix.php');

引用自这里


非常出色——我们的站点地图问题已经困扰我们好几周了,这个绝对解决了它。非常感谢。 - jimiayler
如果您在无法编辑index.php文件的云主机上,则可以在wp-config中包含它以获得相同的结果。 - Dustin Snider

12
你的XML文档以一个换行符开始。

我在哪里可以找到我的站点地图文件?在wp根目录中没有找到。 - Silver Ringvee
1
由于问题涉及到WordPress,因此答案也是如此。两者都与站点地图有关,因此在应用您所建议的内容时,站点地图的位置是一个很好的起点。 - Silver Ringvee

3
每个页面(包括站点地图)的开头都有一个空行。(您可以查看HTML源代码)您应该删除此行以修复站点地图。您可以尝试以下步骤:
检查wp-config.php文件是否存在方括号之外的空白行。
检查您的主题的functions.php文件是否存在方括号之外的空白行。
逐个禁用插件并重新验证,直到确定引起问题的插件(如何检查插件冲突)
请注意,所有PHP代码文件(模块,包括等)中都应省略最终的php ?>。 (例如wp-config.php,functions.php等)。

1

你链接的文章说,为了避免错误,在functions.php文件的末尾不能有超过一行的空白行。 - skybondsor

0

你的主题或插件中包含的一个文件在起始标签<?php之前有一个空白行。

首先,停用所有插件,尝试加载sitemap.xml链接。如果现在可以正常工作,则其中一个插件是罪魁祸首。如果仍然无法正常工作,请继续以下步骤...

其次,逐个检查组成WordPress主题的每个.php文件。找到任何起始标签<?php之前的空白行并删除它们。

第三步,重新安装WordPress核心安装程序。如果仍然无法正常工作,请联系开发人员深入研究您的源代码。


0

问题出在插件文件或函数文件格式不正确,很可能在文件末尾包含了额外的空行。

我通过在一个标签页中打开WordPress插件列表来解决这个问题:

/wp-admin/plugins.php

在第二个选项卡中打开网站地图:

/sitemap_index.xml

然后只需按照这个逻辑一直找到原因:

Deactivate five plugins starting from the top.

if (sitemap shows without errors) {
    Activate four of the latest five to be deactivated and visit the sitemap again.

    if (sitemap shows without errors) { 
        The currently deactivated plugin is at fault. You must reach out to the plugin developer or format the code removing the extra spacing at the beginning or tail of the file.
    else {
        Activate the deactivated plugin and choose one of the other four and deactivate.
    }
} else {
    Reactivate these five deactivated plugins and move onto the next five plugins and deactivate.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接