如何将xml数据附加到xml文件而不使用php覆盖现有数据?

时间:2011-05-31 01:31:39

标签: php xml

HI伙计们,我是php和xml的新手,所以请耐心等待。

我想如何将xml数据附加到xml文件而不用PHP覆盖现有数据。

我这里有代码:

writexml.php

<?php 
 $employees = array(); 

 $employees [] = array( 
  'name' => 'Tom', 
  'age' => '34', 
  'salary' => "$10000" 
 ); 
 $employees [] = array( 
  'name' => 'Ryan', 
  'age' => '20', 
  'salary' => "$2000" 
 ); 
 $employees [] = array( 
  'name' => 'Dave', 
  'age' => '20', 
  'salary' => "$2000" 
 ); 

 $doc = new DOMDocument(); 
 $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 ); 
 } 

 echo $doc->saveXML(); 
 $doc->save("employees.xml") 
?>

当我运行此代码时会发生什么,它会删除所有以前的数据。请帮助。

1 个答案:

答案 0 :(得分:4)

您需要打开现有文档以向其附加信息,您上次保存只会覆盖现有文件。

$doc = new DomDocument();
$doc->loadXML(file_get_contents('employees.xml'));
foreach($doc->getElementsByTagName('employees') as $node)
{
  // your current xml logic here
}

hafedh的更新

$doc = new DomDocument();
$doc->formatOutput = true;
if($xml = file_get_contents('employees.xml'))
  $doc->loadXML($xml);
$nodelist = $doc->getElementsByTagName('employees');
if($nodelist->length === 0)
{
  $nodelist = $doc->createElement("employees"); 
  $doc->appendChild($nodelist);
  $nodelist = $doc->getElementsByTagName('employees');
}
foreach($nodelist as $key => $node)
{
  // Employee Container
  $element = $doc->createElement("employee");
  $employee = $node->appendChild($element);
  // Name Element
  $element = $doc->createElement("name");
  $name = $employee->appendChild($element);
  $element = $doc->createTextNode('CCC');
  $name->appendChild($element);
  // Age Element
  $element = $doc->createElement("age");
  $age = $employee->appendChild($element);
  $element = $doc->createTextNode('333');
  $age->appendChild($element);
}

echo '<pre>' . htmlentities($doc->saveXML());

xml文件内容

<employees><employee><name>AAA</name><age>111</age></employee><employee><name>BBB</name><age>222</age></employee></employees>