S
Seoffix.com
Sign In Get Pro Membership
PHP Advanced
Estimated Duration: 25 min

PHP 8.2: Streaming 50,000 URL XML Sitemaps with Zero Memory

Stream massive Google-compliant XML sitemaps using XMLWriter to keep memory usage under 2MB.

Memory-Efficient XML Generation with XMLWriter


Building massive sitemaps with string concatenation ($xml .= "<url>...") quickly exhausts PHP's memory_limit when handling 50,000 URLs.

PHP's XMLWriter operates as a stream pipeline, writing bytes directly to output buffers without buffering the whole XML DOM in RAM.

In this lesson, you will generate a valid <urlset> containing canonical links, lastmod timestamps, and changefreq attributes.
Target Output
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://seoffix.com/</loc>
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>https://seoffix.com/desk</loc>
    <changefreq>weekly</changefreq>
    <priority>0.9</priority>
  </url>
</urlset>
Need a Hint?
  • Call $xml->startDocument('1.0', 'UTF-8')
  • Open root with $xml->startElement('urlset') and set xmlns attribute
  • Use $xml->writeElement('loc', $u['loc']) for children
solution.php
Terminal Output Ready
Click "Run Code & Test" to execute your solution.