$employees = array();
$employees [] = array(
'name' => 'Albert',
'age' => '34',
'salary' => "$1000000000"
);
$employees [] = array(
'name' => 'Claud',
'age' => '20',
'salary' => "$200000000"
);
$doc = new DOMDocument();
$doc->load('xml/text.xml');
$doc->formatOutput = true;
$r = $doc->createElement( "employees" );
$doc->appendChild( $r );
foreach( $employees as $employee )
{
$b = $doc->createElement( "employee" );
$name = $doc->createElement( "name" );
$name->appendChild(
$doc->createTextNode( $employee['name'] )
);
$b->appendChild( $name );
$age = $doc->createElement( "age" );
$age->appendChild(
$doc->createTextNode( $employee['age'] )
);
$b->appendChild( $age );
$salary = $doc->createElement( "salary" );
$salary->appendChild(
$doc->createTextNode( $employee['salary'] )
);
$b->appendChild( $salary );
$r->appendChild( $b );
}
$doc->save("xml/text.xml")
这个现有的代码加载并将数据写入xml文件,但是现在它不断地一次又一次地创建父节点“employees”。我如何将子节点附加到xml文件中已存在的employees节点?
答案 0 :(得分:0)
假设你已经在xml / text.xml中有一个XML结构,其根节点为'employees',你想要替换这一行:
$r = $doc->createElement( 'employees' );
这一行:
$r = $doc->documentElement;
答案 1 :(得分:0)
假设您的根节点不是employees
,并且只有一个employees
节点,请替换以下行:
$r = $doc->createElement('employees');
$doc->appendChild( $r );
有了这些:
$tags = $doc->getElementsByTagName('employees');
if ($tags->length) {
$r = $tags->item(0);
} else {
$r = $doc->createElement('employees');
$doc->appendChild( $r );
}
此代码使用文档中找到的第一个employees
节点。如果未找到,则将一个附加到文档的末尾。实际上,我猜你想在文档中的某个地方插入employees节点,而不是在最后....