我知道这应该很简单,但我是PHP新手,只是不理解我遇到的文档。我需要一个简单的解释。PHP appendChild到XML根
我有一个XML文档,我想添加节点。我可以将节点添加到文档中,它们只出现在根节点之外,并在随后的尝试中导致错误发生。
这里是我的XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>
,这里是我的PHP:
$playerID = "id_" . $_POST['player'];
//load xml file to edit
$xml = new DOMDocument();
$xml->load('../../saves/playerPositions.xml') or die("Error: Cannot load file.");
//check if the player is already in the database
if(isset($xlm->$playerID)){
echo "Player ID was found.";
}
else{
echo "Player ID was not found.";
//so we want to create a new node with this player information
$playerElement = $xml->createElement($playerID, "");
$playerName = $xml->createElement("name", "John Doe");
//add the name to the playerElement
$playerElement->appendChild($playerName);
//add the playerElement to the document
//THIS IS WHERE THE ERROR OCCURS
$xml->root->appendChild($playerElement);
//save and close the document
$xml->formatOutput = true;
$xml->save("../../saves/playerPositions.xml");
}
echo "done";
如果我只是用$xml->appendChild()
话,我可以修改文档,但新的文本出现的<root></root>
之外。
确切的错误是:
Notice: Undefined property: DOMDocument::$root
你在有哪一个你的实际代码是'$ xml-> root - > ...'或者'$ xml - > $ root - > ...'? – har07
如果我使用$ xml-> root-> appendChild(),那么错误是DOMDocument :: $ root 如果我使用$ xml-> $ root-> appendChild(),那么错误是DOMDocument :: root 但是我我正在使用“root”,因为我知道这是更正确的方式。OP是我的确切代码。 – user1544522
好的,但错误信息不符合代码,因此它是混乱。我用'$ xml-> root'得到的错误信息:*致命错误:调用'null'上的成员函数'appendChild()'* – har07