How to Fix "parser error: XML declaration allowed only at the start of the document" PHP Warning?

If you are seeing the following PHP warning while working with an XML file or string (using SimpleXMLElement):

Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : XML declaration allowed only at the start of the document ...

Then it could mean that your XML document (or string) has space(s) before the first tag. Consider for example, the following, which triggers the warning:

$xmlStr =<<<XML
    <?xml version="1.0"?>
    <customers>
        <customer>
            <name>John Doe</name>
            <age>24</age>
        </customer>
        <customer>
            <name>Jane Doe</name>
            <age>29</age>
        </customer>
    </customers>
XML;

// Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : XML declaration allowed only at the start of the document ...
$xml = new SimpleXMLElement($xmlStr);
// ...

To fix this issue, you simply need to remove the space before the first tag, for example, like so:

$xmlStr =<<<XML
<?xml version="1.0"?>
    <customers>
        <customer>
            <name>John Doe</name>
            <age>24</age>
        </customer>
        <customer>
            <name>Jane Doe</name>
            <age>29</age>
        </customer>
    </customers>
XML;

$xml = new SimpleXMLElement($xmlStr);
// ...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.