This code snippet fixed it for us. Add to your functions.php:
// Hook into the wpseo_sitemap_index action
add_action('wpseo_sitemap_index', 'custom_modify_sitemap_output');
function custom_modify_sitemap_output() {
// Start output buffering
ob_start('custom_modify_sitemap_buffer');
// Call the Yoast SEO sitemap index function
do_action('wpseo_xml_sitemap_index', 'always', true);
// End output buffering and get the modified sitemap content
$modified_sitemap_content = ob_get_clean();
// Log the original and modified sitemap content
error_log('Original sitemap content: ' . ob_get_clean());
error_log('Modified sitemap content: ' . $modified_sitemap_content);
// Output the modified sitemap content
echo $modified_sitemap_content;
}
function custom_modify_sitemap_buffer($buffer) {
// Remove any whitespace before the XML declaration
$buffer = preg_replace('/^\s+/', '', $buffer);
// Ensure the XML declaration is at the beginning
if (strpos($buffer, '<?xml') !== 0) {
$buffer = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $buffer;
}
return $buffer;
}