我知道這應該很簡單,但我是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