This page contains the following error: error on line 1 at column 1: Document is empty

This page contains the following error: error on line 1 at column 1: Document is empty

我找不到解决办法,请帮忙。下面是代码。提前致谢

   <?php
require_once('connect.php');



$sql = "select * from projet";
$result = $conn->query($sql);
$xml = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
  $mydata = $xml->addChild('mydata');
    $mydata->addChild('Id',$row['idProjet']);
     }
} else {
echo "0 results";
}
$conn->close();
header ("Content-Type:text/xml");
 echo($xml->asXML());
?>

和文件 connect.php

   $servername = "localhost";
$username = "root";
$password = "";
$dbname = "mtocrowdrise";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "connected succesfully";    

与此同时,我不断收到此错误:

  This page contains the following errors:

error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error. 

当所述页面被转换为 XML 文档 (header ("Content-Type:text/xml");) 时,你不应该 writing/outputting 任何 HTML 页面。

connect.php 中删除 echo "connected succesfully";

如果出现以下情况,您也会(最终)遇到同样的错误:

...
} else {
    echo "0 results";
}
...
header ("Content-Type:text/xml");

满足。因此,如果没有错误并且实际上有一些 XML 要显示,您应该只将文档转换为 XML。

如果有要显示的结果(根据您的原始代码),类似下面的内容只会将文档设置为 XML:

require_once('connect.php');

$sql = "select * from projet";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $xml = new SimpleXMLElement('<xml/>');
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $mydata = $xml->addChild('mydata');
        $mydata->addChild('Id',$row['idProjet']);
    }
    header ("Content-Type:text/xml");
    echo($xml->asXML());
} else {
    echo "0 results";
}
$conn->close();