【发布时间】:2016-10-02 04:35:05
【问题描述】:
我知道这应该很简单,但我是 PHP 新手,只是不了解我遇到的文档。我需要一个简单的解释。
我有一个想要添加节点的 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>之外。
确切的错误是:
注意:未定义的属性:DOMDocument::$root
【问题讨论】:
-
您的实际代码中有哪一个,
$xml->root->...或$xml->$root->...? -
如果我使用 $xml->root->appendChild() 那么错误是 DOMDocument::$root 如果我使用 $xml->$root->appendChild() 那么错误是 DOMDocument: :root 但我使用的是“root”,因为我知道这是更正确的做法。 OP 是我的确切代码。
-
好的,但是错误信息与代码不对应,因此令人困惑。我收到
$xml->root的错误消息:致命错误:在null上调用成员函数appendChild()
标签: php xml appendchild