wordpress的sitemap.xml报错error on line 4 at column 6: XML declaration allowed only at the start of the document

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

wordpress使用wp-sitemap.php配合nginx重写规则实现wp-sitemap.xml网站地图时,典型报错

报错信息:
This page contains the following errors:
error on line 4 at column 6: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.

解决办法:
1、点此下载solvesitemapserror文件(是一个zip压缩包),解压后得到一个solvesitemapserror.php文件,这个php文件的代码作用是删除生成的xml文件的不必要的空格等符号,使之满足xml格式要求,solvesitemapserror.php代码如下(只是给你看看,不需要将代码加入任何地方):


function ___wejns_wp_whitespace_fix($input) {
/* valid content-type? */
$allowed = false;

/* found content-type header? */
$found = false;

/* we mangle the output if (and only if) output type is text/* */
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;
}
}

/* do the actual work */
if ($allowed || !$found) {
return preg_replace("/\\A\\s*/m", "", $input);
} else {
return $input;
}
}

/* start output buffering using custom callback */
ob_start("___wejns_wp_whitespace_fix");

2、打开网站的根目录,将solvesitemapserror.php文件上传到根目录,如下图所示:

3、编辑根目录下的index.php文件(注意不是你wordpress主题的index.php),在index.php开头加入一段引入代码:
include("solvesitemapserror.php");//解决站点地图报错问题,引用此文件
然后保存退出编辑。

4、重启服务器php服务,如果是lnmp搭建的,命令应该是 lnmp php-fpm restart ,执行完后去刷新http://yourdomain.com/sitemap.xml 应该就正常了。