【问题标题】:simplexml_load_file : XML declaration allowed only at the start of the documentsimplexml_load_file : 只允许在文档开头的 XML 声明
【发布时间】:2013-01-29 17:16:55
【问题描述】:

我想用 SimpleXML 解析 PHP 中的 XML 文档。 我使用了simplexml_load_file,我得到了这个错误:

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

我在 Google 上搜索过,问题似乎是 XML 文档中的标签前有一些空格。我查了一下,之前没有空格。

这是我的代码:

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;
}

编辑:错误是Failed loading XML XML declaration allowed only at the start of the document Extra content at the end of the document

XML 文档的第一个标签是&lt;?xml version="1.0" encoding="UTF-8"?&gt;

【问题讨论】:

  • 您的 XML 文件来源在哪里?
  • 两个子目录之后。

标签: php xml parsing simplexml


【解决方案1】:

按照 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>

问题出在第一行的注释上!

【讨论】:

    【解决方案2】:

    假设,我发现(实际上我第一次遇到这个错误)。

    1. 我尝试了一个以 &lt;?xml ... 开头的 XML 文件(没有错误)
    2. 我尝试了一个以 [space or/and new line]&lt;?xml ... 开头的 XML 文件(有错误)

    // 两个错误(xml.xml 内容)

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

    所以,请确保 XML 文件以 &lt;?xml ... 或有效的 XML 标记(我的意思是 1. 行)开头,从第一行删除所有空格。

    【讨论】:

      【解决方案3】:

      从头开始去掉空格:

      new \SimpleXMLElement(
        trim($xmlString)
      );
      

      它对我有用。

      【讨论】:

        【解决方案4】:

        先声明$xsml,然后在if中使用。

        【讨论】:

          猜你喜欢
          • 2013-02-25
          • 1970-01-01
          • 2012-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-06
          相关资源
          最近更新 更多