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

Fix for "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);
// ...

Hope you found this post useful. It was published . Please show your love and support by sharing this post.