php XML 解析错误:找不到根元素位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42756240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:42:27  来源:igfitidea点击:

XML Parsing Error: no root element found Location

phpxmlhtmlweb-applicationsxml-parsing

提问by Edgar Serna

So I'm making a simple login/registration web application but I keep getting the following error:

所以我正在制作一个简单的登录/注册 Web 应用程序,但我不断收到以下错误:

XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:   

and

XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:

here is my login.php

这是我的 login.php

<?php
header('Content-type: application/json');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    header('HTTP/1.1 500 Bad connection to Database');
    die("The server is down, we couldn't establish the DB connection");
}
else {
    $conn ->set_charset('utf8_general_ci');
    $userName = $_POST['username'];
    $userPassword = $_POST['userPassword'];

    $sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
        }
        echo json_encode($response);
    }
    else {
        header('HTTP/1.1 406 User not found');
        die("Wrong credentials provided!");
    }
}
$conn->close();
?>

I've done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox

我已经对 xml 解析错误进行了一些研究,但我仍然无法使我的项目正常工作,我尝试过使用 Google Chrome 和 Firefox

回答by mike rodent

AHA! Got this today for a reason which will make me look pretty silly but which mightone day help someone.

啊哈!今天得到这个的原因会让我看起来很傻,但有一天可能会帮助某人。

Having set up an Apache server on my machine, with PHP and so on... I got this error... and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed "file:///D:/apps/Apache24/htdocs/experiments/forms/index.html".

在我的机器上设置了一个 Apache 服务器,使用 PHP 等等......我收到了这个错误......然后意识到了原因:我点击了有问题的 HTML 文件(即包含 Javascript/JQuery 的文件),所以浏览器中的地址栏显示“file:///D:/apps/Apache24/htdocs/experiments/forms/index.html”。

What you have to do to actually use the Apache server (assuming it's running, etc.) is go "http://localhost/experiments/forms/index.html"in the browser's address bar.

要实际使用 Apache 服务器(假设它正在运行等),您需要做的是在浏览器的地址栏中输入http://localhost/experiments/forms/index.html

In mitigation I have up to now been using an "index.php" file and just changed to an "index.html" file. Bit of a gotcha, since with the former you are obliged to access it "properly" using localhost.

在缓解方面,我到目前为止一直使用“index.php”文件,只是更改为“index.html”文件。有点问题,因为对于前者,您必须使用本地主机“正确”访问它。

回答by Raj

I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue

我在 Spring MVC 应用程序中遇到了同样的情况,因为它被声明为无效,将其更改为返回字符串解决了这个问题

@PostMapping()
public void aPostMethod(@RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body); 
}

To

@PostMapping()
public String aPostMethod(@RequestBody( required = false) String body) throws IOException {
    System.out.println("DoSome thing" + body);
    return "justReturn something";
}

回答by Yolo

Assuming you are working with javascript, you need to put a header in front of echoing your data:

假设您正在使用 javascript,您需要在回显数据前放置一个标题:

header('Content-Type: application/json');
echo json_encode($response);

回答by Midimistro

Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.

确保您的 php 服务器正在运行,并且 php 代码位于适当的文件夹中。如果 php 不存在,我会遇到同样的问题。我还建议将您的 html 放在同一个文件夹中,以防止在测试时出现跨域错误。

If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.

如果这不是问题,请确保 php 中的每个 SQL 调用都是正确的,并且您使用的是当前的 php 标准... php 变化很快,不像 html、css 和 Javascript,因此某些功能可能会被弃用。

Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:

另外,我注意到您可能没有正确收集变量,这也可能导致此错误。如果您通过表单发送变量,则它们需要采用正确的格式并根据您的偏好通过 POST 或 GET 发送。例如,如果我有一个迷宫游戏的登录页面:

HTML

HTML

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <form class="modal-content animate" method="post">
    <div class="container">
        <label><b>Username</b></label>
        <input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
        <label><b>Password</b></label>
        <input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
        <button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
        <button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
    </div>
    </form>

JavaScript

JavaScript

function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
    url: 'makeUserEntry.php',
    type: 'POST',
    data: datasend,
    success: function(response, status) {
        if(response=="Username or Password did not match"){
            alert("Username or Password did not match");
        }
        if(response=="Connection Failure"){
            alert("Connection Failure");
        }
        else{
            localStorage.userid = response;
            window.location.href = "./maze.html"
        }
    },
    error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
        var response = xhr.responseText;
        console.log(response);
        var statusMessage = xhr.status + ' ' + xhr.statusText;
        var message  = 'Query failed, php script returned this status: ';
        var message = message + statusMessage + ' response: ' + response;
        alert(message);
    }
}); // end ajax call
}

PHP

PHP

<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];


//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
    die("Connection Failed:  " . $conn->connect_error);
    echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
    $userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
    $userID = $conn->query($userIDSQL);
    echo json_encode($userID);
}
else{
    echo json_encode("Username or Password did not match");
}

$conn->close();
?>

It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!

如果您包含代码的其他部分(例如 html 和 JavaScript)会有所帮助,因为我不必像这样给出自己的示例。但是,我希望这些指针有所帮助!