Using XSLT to Transform XML for Web Applications
Your supplier sends a perfectly readable XML file. Your website needs a product list. Between those two sits a familiar development problem: turning structured data into something people can use without losing values, exposing private fields, or breaking the layout. XSLT gives you a repeatable way to make that conversion. A stylesheet selects information from XML, applies templates, and produces HTML, another XML structure, or plain text.
From XML to Reliable Output: Start with a small sample and a clear output contract. Build templates that select only the fields your application needs. Check the resulting structure, text, encoding, and missing values before connecting the transformation to a live request. Keep original files intact, use synthetic data for unfamiliar tools, and test with the same processor your server runs. A successful transformation still needs checks for correctness, privacy, and browser behavior.
Define What the Transformation Should Produce
Before writing a stylesheet, describe the result in plain language. For a catalog, that might mean one product card for each active product, a title, and a price. Internal supplier notes should stay out of the result.
This small agreement becomes your output contract. It tells you which records belong, which fields are required, and how missing information should appear. Without it, a transformation can run successfully while producing the wrong content.
XSLT processes a parsed document tree. XPath expressions select nodes within that tree. Templates describe what to create when selected nodes match particular rules. The official transformation specification defines this processing model and the output methods available in XSLT 1.0.
Keep your first task narrow. Converting a catalog into an HTML fragment is easier to verify than changing its structure, translating descriptions, calculating taxes, and creating download files in one stylesheet.
Build a Small XML Sample You Can Check Yourself
Use invented records while developing the transformation. Two products are enough to test filtering and escaping:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<product id="p101" active="true">
<name>Desk Lamp & Stand</name>
<price currency="USD">29.90</price>
<internalNote>Sample supplier note</internalNote>
</product>
<product id="p102" active="false">
<name>Travel Mug</name>
<price currency="USD">12.50</price>
</product>
</catalog>
The expected result contains the desk lamp and excludes the travel mug. It also excludes the internal note. The product name should display an ampersand in the browser.
Preserve the original XML separately. Transformation output is often selective, which makes it unsuitable as a replacement archive. Once a field has been omitted, you cannot reconstruct it from the HTML.
Keep identifiers as strings unless arithmetic is required. A product code of 00125 can lose its leading zeros if treated as a number. Dates, decimal values, and currency codes also need explicit handling rather than assumptions based on how they look.
Create Templates That Select and Render Products
This XSLT 1.0 stylesheet converts the sample into an HTML fragment. Save it separately as catalog.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"
encoding="UTF-8"
omit-xml-declaration="yes"/>
<xsl:template match="/">
<section class="catalog">
<h2>Available Products</h2>
<xsl:choose>
<xsl:when test="catalog/product[@active='true']">
<xsl:apply-templates
select="catalog/product[@active='true']"/>
</xsl:when>
<xsl:otherwise>
<p>No products are available.</p>
</xsl:otherwise>
</xsl:choose>
</section>
</xsl:template>
<xsl:template match="product">
<article class="product">
<h3><xsl:value-of select="name"/></h3>
<p>
<xsl:value-of select="price/@currency"/>
<xsl:text> </xsl:text>
<xsl:value-of select="price"/>
</p>
</article>
</xsl:template>
</xsl:stylesheet>
The first template matches the document root. It creates a container and selects active products. The second template handles each selected product. This separation keeps record selection apart from record presentation.
xsl:value-of inserts text values. The serializer escapes characters where required. Avoid disable-output-escaping for ordinary data. A product name should remain text, even if its value contains markup characters.
The stylesheet deliberately selects individual fields. Broad copying can carry unwanted elements or attributes into the result. Explicit selection also makes a privacy review easier because you can see exactly what becomes public.
Match Output Format to the Receiving Application
The correct output method depends on what consumes the result. A browser fragment, an XML import, and a text export have different requirements. Renaming a file does not change its format.
Output Methods and Their Checks
| Method | Suitable Result | Primary Check |
|---|---|---|
| HTML | Product cards or report fragments | Inspect HTML structure, displayed text, and browser rendering. |
| XML | A document for another system | Parse the result and validate against the receiving schema when available. |
| Text | Plain text reports or controlled exports | Check separators, line endings, encoding, and escaping rules. |
Text output does not automatically create valid CSV. Values containing commas, quotation marks, or line breaks need CSV-specific quoting. Decide whether that work belongs in the stylesheet or in a dedicated export library.
For HTML responses, align the HTTP content type and charset with the generated bytes. UTF-8 in the stylesheet is only part of that agreement. The surrounding PHP response and any stored output must preserve it too.
Check Results Beyond a Successful Run
A processor accepting your stylesheet proves that it could execute the transformation. It does not prove that every expected product appeared or that prices stayed attached to the correct names.
Use a few direct assertions against the result:
- Confirm that the number of product cards matches the number of eligible input records.
- Check that excluded records and private fields do not appear anywhere in the output.
- Verify names containing ampersands, accented letters, and non-Latin characters.
- Check the agreed behavior for absent names, empty prices, and an empty catalog.
- Inspect generated attributes and URLs if later templates introduce links or images.
Check structure with an HTML parser as well as viewing the page. Browsers can repair malformed HTML, hiding defects in the original output. For XML output, require successful parsing before attempting schema validation.
Keep structural validation separate from business checks. A schema may permit a decimal price without knowing whether that price belongs to the correct product. Your tests must cover both questions.
Test Compatibility and Privacy Before Integration
Run a synthetic sample through an XSLT transformer when you want to examine template behavior. Before entering real records into any unfamiliar tool, verify where processing happens, whether files leave your device, and what retention policy applies. A browser interface alone does not establish local processing.
Avoid using customer exports for experiments. Replace names, addresses, credentials, and internal notes with invented values. Include awkward characters and missing fields in that synthetic data so privacy does not come at the expense of useful testing.
Processor compatibility needs its own check. A stylesheet that depends on XSLT 2.0 or 3.0 features will not become compatible with an XSLT 1.0 processor merely by changing its version attribute. PHP’s commonly used libxslt-backed XSL extension runs XSLT 1.0, so confirm the actual runtime before adopting examples written for later versions.
Namespaces can cause an apparently empty result. If the source declares a default namespace, an unprefixed XPath such as catalog/product will not match those elements in XSLT 1.0. Bind the source namespace to a prefix in the stylesheet and use that prefix in selections and match patterns.
Connect the Stylesheet to PHP With Clear Boundaries
Keep stylesheets under application control. Accepting arbitrary uploaded stylesheets creates a much larger execution surface than transforming uploaded XML with a reviewed stylesheet.
Load the source and stylesheet into separate DOMDocument instances. Check each load result before calling XSLTProcessor::importStylesheet(). Check that import succeeds, then inspect the return value from transformToXML(). Treat false as failure rather than returning an empty success response.
Configure parser behavior explicitly. Use LIBXML_NONET to block network access during parsing, avoid enabling external entity substitution or external DTD loading, and reject document types when your input contract does not require them. Network restrictions alone do not block every possible local file access.
Set transformation restrictions before importing and running the stylesheet. PHP documents configurable file and network restrictions through security preferences. For a self-contained stylesheet, a restrictive configuration can combine these flags:
$processor = new XSLTProcessor();
$processor->setSecurityPrefs(
XSL_SECPREF_READ_FILE |
XSL_SECPREF_WRITE_FILE |
XSL_SECPREF_CREATE_DIRECTORY |
XSL_SECPREF_READ_NETWORK |
XSL_SECPREF_WRITE_NETWORK
);
These flags restrict processor operations. They do not replace secure XML loading or review of stylesheet dependencies. Avoid registering PHP callbacks unless your design specifically requires them. Add input size limits and execution limits because expensive transformations can consume substantial memory or processing time.
Rehearse the Application Path Before Release
Use a repeatable release sequence instead of checking a single happy example:
- Save synthetic input files and their expected results beside the stylesheet.
- Run them through the same processor and configuration used by the application.
- Check parsing, selected records, required fields, escaping, and sensitive-data exclusion.
- Render the resulting fragment inside the real page layout in a test environment.
- Measure execution with realistic file sizes and verify failure handling.
- Release with the previous stylesheet available for rollback.
Keep error details out of public responses. Parser messages can contain filesystem paths or source content. Record only the diagnostics your team needs, with access controls and suitable redaction.
If transformed fragments are cached, include the stylesheet version and relevant parameters in the cache key. Otherwise, a corrected template may appear ineffective because the application keeps serving earlier output.
Give Every Generated Page a Traceable Starting Point
A dependable XML transformation leaves you able to answer three questions: which input produced this result, which stylesheet ran, and which checks passed? Preserve source files, version your templates, and keep representative test cases.
Start with one clear conversion. Inspect its output closely. Then connect it to the application with controlled parsing, restricted processing, and predictable failure handling. That makes XSLT a manageable part of your PHP workflow, with results you can explain and reproduce.
No Responses