使用php更新xml中的节点属性

时间:2013-04-17 11:31:03

标签: php xml simplexml

是否可以使用simplexml更新xml的节点属性? 例如:-my程序实际上是教师的测验编辑器,作为教师,我想编辑特定的问题属性。即

<Quiz>
<topic text="Preparation for Exam">
    <subtopic text="Math">
              <question text="1 + 1 = ?"> 
              <answer num="A" Text="1" /> 
              <answer num="B" Text="2" /> 
              <answer num="C" Text="3" /> 
              <answer num="D" Text="4" /> 
              </question>
              <question text="4 * 4 = ?" > 
              <answer num="A" Text="12" /> 
              <answer num="B" Text="14" /> 
              <answer num="C" Text="16" /> 
              <answer num="D" Text="18" /> 
              </question>
       </subtopic>
       </topic>
       </Quiz>

有可能吗?虽然我已经尝试了很多方法,即删除前一个节点然后插入编辑过的节点。但这个技巧只适用于最后一个节点...对于其他节点,它只是交换

1 个答案:

答案 0 :(得分:0)

<?php
$subtopic = new SimpleXMLELement(data());
$subtopic->question[1]['text'] = 'lalala';
$subtopic->question[1]['foo'] = 'bar';

foreach( $subtopic->question[1]->answer as $answer) {
    $answer['Text'] .= '(dez)';
}

echo $subtopic->asXML();


function data() {
    return <<< eox
<subtopic text="Math">
<question text="1 + 1 = ?"> 
<answer num="A" Text="1" /> 
<answer num="B" Text="2" /> 
<answer num="C" Text="3" /> 
<answer num="D" Text="4" /> 
</question>
<question text="4 * 4 = ?" > 
<answer num="A" Text="12" /> 
<answer num="B" Text="14" /> 
<answer num="C" Text="16" /> 
<answer num="D" Text="18" /> 
</question>
</subtopic>
eox;
}

打印

<?xml version="1.0"?>
<subtopic text="Math">
<question text="1 + 1 = ?"> 
<answer num="A" Text="1"/> 
<answer num="B" Text="2"/> 
<answer num="C" Text="3"/> 
<answer num="D" Text="4"/> 
</question>
<question text="lalala" foo="bar"> 
<answer num="A" Text="12(dez)"/> 
<answer num="B" Text="14(dez)"/> 
<answer num="C" Text="16(dez)"/> 
<answer num="D" Text="18(dez)"/> 
</question>
</subtopic>