What are some common pitfalls to avoid when using PHP to create dynamic sitemaps?

One common pitfall to avoid when using PHP to create dynamic sitemaps is not properly escaping special characters in URLs. This can lead to invalid URLs in the sitemap, causing issues with search engine indexing. To solve this, make sure to use the urlencode() function to encode URLs before adding them to the sitemap.

$url = 'https://example.com/page with spaces';
$encoded_url = urlencode($url);
echo '<url><loc>' . $encoded_url . '</loc></url>';