0

I want to parse an XML document in PHP with SimpleXML. I used simplexml_load_file and I got this error:

Warning: simplexml_load_file(): [myfile] parser error : XML declaration allowed only at the start of the document in /www/[...]/myphpfile.php on line 7

I have searched on Google and the problem seems to be that there is some whitespace before the tags in the XML document. I checked, there is no whitespace before.

Here is my code:

libxml_use_internal_errors(true);
$sxml=simplexml_load_file($xml);
if ($sxml) {
 echo '<h2>'.$xml.'</h2>';
 echo '<p>author: <textarea>';
 foreach($sxml->author as $author) {
  if($author!=$strXML)
   echo $author.'\n';
  }
  echo '</textarea></p>';
}else {
  echo "Failed loading XML\n";
  foreach(libxml_get_errors() as $error)
    echo "\t", $error->message;
}

Edit: error is Failed loading XML XML declaration allowed only at the start of the document Extra content at the end of the document

The first tag of the XML document is <?xml version="1.0" encoding="UTF-8"?>

2
  • Where is your XML file source?
    – Kerem
    Jan 29, 2013 at 17:53
  • Two children directory after.
    – vekah
    Jan 29, 2013 at 18:19

4 Answers 4

4

I got this error following an example from Symfony2 :

<!-- validators.en.xliff -->
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="1">
                <source>author.name.not_blank</source>
                <target>Saisissez un nom</target>
            </trans-unit>
        </body>
    </file>
</xliff>

The problem was the comment on the first line !

2

Suppose, I found (actually I meet this error first time).

  1. I tried an XML file that start very first line with <?xml ... (no error)
  2. I tried an XML file that start very first line with [space or/and new line]<?xml ... (has error)

// both error (xml.xml contents)


<?xml version="1.0" encoding="UTF-8"?>
<response>
// and
 <?xml version="1.0" encoding="UTF-8"?>
<response>


$xml = simplexml_load_file("xml.xml");
$xml = new SimpleXMLElement(file_get_contents("xml.xml"));

So, be sure XML file starts with <?xml ... or a valid XML tags (I mean 1. line), remove all spaces from first line.

1

Just strip whitespaces from beginning:

new \SimpleXMLElement(
  trim($xmlString)
);

It worked for me.

0

Declare the $xsml first then use it in the if.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.