在关闭节点之前添加一个XML节点
问题描述:
我需要在关闭节点之前添加我的XML树,我似乎无法找到解决方案。红色块中的示例仅需要移动到</quiz>
节点之上。在关闭节点之前添加一个XML节点
这在PHP它创建XML的红色块上面的部分完成了我的XML代码。
$xml = simplexml_load_file('quiz.xml');
$questionLoad = $xml->addChild('question');
$textQue = $questionLoad->addChild('text', $que);
$optionNode = $questionLoad->addChild('option');
$ans1 = $optionNode->addChild('text', $answer1);
$score = $optionNode->addChild('score', $score1);
$explain = $optionNode->addChild('explanation');
$expl1 = $explain->addChild('text', $explanation1);
$xml->asXML('quiz.xml');
答
对于一个给定的输入quiz.xml
有适合您的代码
<?php
$que = 'fsa';
$answer1 = 'cs';
$score1 = 5;
$explanation1 = 'hgfhfg';
$xml = simplexml_load_file('quiz.xml');
$questionLoad = $xml->children()[0]->addChild('question');
$textQue = $questionLoad->addChild('text', $que);
$optionNode = $questionLoad->addChild('option');
$ans1 = $optionNode->addChild('text', $answer1);
$score = $optionNode->addChild('score', $score1);
$explain = $optionNode->addChild('explanation');
$expl1 = $explain->addChild('text', $explanation1);
$xml->asXML('quiz.xml');
以下的PHP的
<?xml version="1.0"?>
<quizzes>
<quiz>
<question>
<text>Choose the correct word for hot + est</text>
<option>
<text>hottest</text>
<score>5</score>
<explanation>
<text>Correct!</text>
</explanation>
</option>
<option>
<text>hotestt</text>
<score>0</score>
<explanation>
<text>Incorrect!</text>
</explanation>
</option>
<option>
<text>hotest</text>
<score>0</score>
<explanation>
<text>Incorrect!</text>
</explanation>
</option>
</question>
</quiz>
</quizzes>
内容产生想要的结果
<?xml version="1.0"?>
<quizzes>
<quiz>
<question>
<text>Choose the correct word for hot + est</text>
<option>
<text>hottest</text>
<score>5</score>
<explanation>
<text>Correct!</text>
</explanation>
</option>
<option>
<text>hotestt</text>
<score>0</score>
<explanation>
<text>Incorrect!</text>
</explanation>
</option>
<option>
<text>hotest</text>
<score>0</score>
<explanation>
<text>Incorrect!</text>
</explanation>
</option>
</question>
<question><text>fsa</text><option><text>cs</text><score>5</score><explanation><text>hgfhfg</text></explanation></option></question></quiz>
</quizzes>
+0
非常感谢!这是我需要的。 – mrAfzaL
答
在上面的代码
要装入一个XML和简单添加节点,这将总是在文件的结尾加入。
尝试使用附加,而不是增加对前:
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
仅供参考。
_“样品
quiz.xml
下面的红色块只需要移动到''n ode。“_ - 没有像”closing _node_“这样的东西,只有一个结束_tag_。如果你想追加一个元素作为现有节点的最后一个子元素,那么使用appendChild。 – CBroe