simplexml_load_file:仅在文档开头允许XML声明

问题描述 投票:0回答:4

我想用PHP解析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文档的第一个标记是<?xml version="1.0" encoding="UTF-8"?>

php xml parsing simplexml
4个回答
4
投票

我从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. 我尝试了一个用<?xml ...开始第一行的XML文件(没有错误)
  2. 我尝试了一个用[space or/and new line]<?xml ...开始第一行的XML文件(有错误)

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


<?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"));

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


0
投票

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


0
投票

从开头开始删除空格:

new \SimpleXMLElement(
  trim($xmlString)
);

它对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.