October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Fix “XML Declaration Allowed Only at the Start of the Document” in PHP

The PHP XML declaration error means a declaration appeared after document content. Trace the exact input and use the fix for leading output, fragments, encoding, or multiple documents.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This PHP error means the parser found an XML declaration such as <?xml version="1.0"?> after the document had already started. Find what precedes that declaration or why another one appears, then correct the input: remove only confirmed accidental leading bytes, omit declarations from embedded fragments, or process concatenated documents separately. The XML declaration belongs at the start of an XML document, as specified by the W3C XML 1.0 specification.

First identify what PHP is parsing

Locate the failing operation and inspect the exact string or response body it receives. This can happen with SimpleXML, DOMDocument::loadXML(), XMLReader, or a fragment operation such as DOMDocumentFragment::appendXML(). PHP’s SimpleXML examples show construction from an XML string, and the DOMDocument::loadXML() manual documents loading XML from a string.

As an Amazon Associate I earn from qualifying purchases.

  • For a string, search for every occurrence of <?xml and check what appears before the first one.
  • Inspect the original bytes, not only a copy pasted into an editor. Leading whitespace, a byte-order mark (BOM), or output from another part of the application may be hard to spot visually.
  • For a remote feed, inspect or save the response body. Confirm it is XML rather than an error page, debug text, or a response containing mixed content. An XMLReader error example describes this issue in a large-feed context.

Once you know whether the bad data is incoming or generated by your own endpoint, use the matching fix below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix leading bytes or output before the declaration

If one XML document has whitespace or other content before its declaration, remove the unintended content at its source. In a PHP endpoint, inspect included files and every output path for stray whitespace, debug statements, warnings, or other output emitted before the XML body. The response should contain one XML document, beginning with its permitted declaration if one is included.

For a known string where the only unwanted prefix is whitespace, trimming may be sufficient:

$xml = trim($xml);
$document = new SimpleXMLElement($xml);

Use this only when you have established that the prefix is disposable whitespace. It will not fix a second declaration, arbitrary text, an encoding mismatch, or multiple document roots. Avoid broad byte stripping that could silently discard meaningful content.

If you suspect a UTF-8 BOM, confirm its presence at the byte level and remove it only when present. Do not assume every PHP/libxml deployment handles BOMs identically; test the actual environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep declarations out of embedded XML fragments

An XML fragment inserted into an existing document is not a second standalone document. Include its element markup, but not an XML declaration. For example:

$fragment = '<customer><name>Example</name></customer>'; // UTF-8; no XML declaration
$ok = $target->appendXML($fragment);

For DOMDocumentFragment::appendXML(), the fragment content is expected to be UTF-8. An encoding declaration inside the fragment does not convert its bytes or make a differently encoded fragment compatible with the parent. Determine the fragment’s actual encoding and transcode it to UTF-8 before appending. This distinction is documented in the historical PHP Bug #38483 report; it describes that specific behavior and should not be read as a guarantee about every current PHP version.

Process concatenated XML documents as separate inputs

If the input is several complete XML documents joined together, deleting later declarations is not enough. A single XML document still needs one valid document structure, and simply removing declarations can leave multiple root elements.

  • If the documents are meant to remain independent, split or stream them as separate inputs and parse each one separately.
  • If their contents are meant to form one document, extract valid element content and place it under one outer root element, with the outer document’s declaration at the beginning at most.

Choose based on what the data represents; do not discard declarations until you know whether the input is a fragment or a sequence of complete documents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Parse a correctly formed whole-document string

A standalone XML string can begin with its declaration and then be passed to SimpleXML:

$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<customers><customer><name>Example</name></customer></customers>
XML;

$document = new SimpleXMLElement($xml);

If the corrected input still fails, inspect the exact bytes again and verify that the document has one valid root and that any declared encoding matches the bytes. The declaration’s position is a document-structure issue; changing the PHP parser call alone does not repair malformed input.

Choose the fix by the shape of the data

What you found Appropriate fix
One document with confirmed accidental leading whitespace or output Remove the unintended prefix at the producer; trim only a known whitespace-only prefix.
One document with a confirmed BOM Detect and remove that BOM explicitly, preserving all other bytes.
An XML fragment inserted into another document Omit the fragment declaration and provide UTF-8 content to appendXML().
Multiple complete XML documents concatenated together Parse them separately, or transform their valid contents into one document with one root.
An endpoint returning XML mixed with debug text or warnings Correct output paths so only the intended XML document is emitted.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.