ThePixelDeveloper/Sitemap

Feature Request: allow adding XML processing instructions to enable support for XSLT

holtkamp opened this issue · 5 comments

First of all a big thanks for this great library, drastically reduces complexity in generating XML Sitemaps!

When migrating our home-brew DOMDocument based functionality, I noticed that currently it is not possible to inject "Processing Instructions" into the XML. This can be useful to add XML like:

<?xml-stylesheet type="text/xsl" href="/path/to/xslt/main-sitemap.xsl"?>

When an browser that supports XSLT opens such a sitemap, it applies the transformation as defined in the XSLT. We use that to make the sitemap human-readable for non-techies.

For example:

Also see

I could not find a way to hook into the XMLWriter object to inject such processing instructions.

Workaround
A dirty workaround that works for now is (using DOMDocument):

$xml =  (new Thepixeldeveloper\Sitemap\Output())->getOutput($sitemapIndex);
$doc = new DOMDocument();
$doc->loadXML($xml);
$xslt = $doc->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="/path/to/xslt/main-sitemap.xsl"');
$doc->insertBefore($xslt, $doc->documentElement); //Insert before the root element
echo $doc->saveXML();

Thanks for the report. Will see if I can get something done today.

@holtkamp Released 4.4.1 with support for processing instructions. See the README for usage instructions. Thanks for using the library.

Great, composer just installed that latest version, gave it a shot, but it seems the Processing Instructions are rendered before the <?xml version="1.0" encoding="UTF-8"?>

for example:

<?xml-stylesheet type="text/xsl" href="/public/xslt/main-sitemap.xsl"?>
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    ...
</sitemapindex>

This results in an error like:

XML Parsing Error: XML or text declaration not at start of entity
Location: https://www.domain.ext/sitemap
Line Number 2, Column 1:<?xml version="1.0" encoding="UTF-8"?>

Maybe this section needs to be after startDocument()?

Sitemap/src/Output.php

Lines 48 to 50 in cb80252

foreach ($this->processingInstructions as $target => $content) {
$xmlWriter->writePi($target, $content);
}

@holtkamp Wups. Fixed and tagged as 4.4.2

awesome, works like a charm! Thanks!