2009-12-15 9 views
0

XML 파일을 편집하고 </user>의 끝에 새 항목을 추가하려면 어떻게합니까? PHP XML에 새 항목 추가

<FileZillaServer> 
<Users> 
<User Name="test"> 
</User> 
/* using php to add another users on here <User Name="test2" */ 
</Users> 
</FileZillaServer> 

도움을 주셔서 감사합니다 같은

내 XML (FileZilla의)를 찾습니다.

답변

1

DOMDocument 클래스를 사용하여 XML 문서를 조작 할 수 있습니다.

는 예를 들어, 다음과 같이 사용할 수 있습니다

$str = <<<XML 
<FileZillaServer> 
    <Users> 
     <User Name="test"> 
     </User> 
    </Users> 
</FileZillaServer> 
XML; 

$xml = DOMDocument::loadXML($str); 
$users = $xml->getElementsByTagName('Users'); 

$newUser = $xml->createElement('User'); 
$newUser->setAttribute('name', 'test2'); 
$users->item($users->length - 1)->appendChild($newUser); 

var_dump($xml->saveXML()); 

당신 얻을 것이다 어떤 : 당신 즉

string '<?xml version="1.0"?> 
<FileZillaServer> 
    <Users> 
     <User Name="test"> 
     </User> 
    <User name="test2"/></Users> 
</FileZillaServer> 
' (length=147) 

:

  • 새로운 User 요소를 생성
  • 너는 name attr을 설정했다. ibute
  • 당신은

새로운 요소 Users은 (length의 사용을 피하고 그렇게 할 수있는 다른 방법은, 아마이 있다는 것을 추가; 하지만 이것은 내가 처음 생각한 것입니다 - 아주 이른 아침에 ^^)

0

사용 SimpleXML. 이름에서 알 수 있듯이 XML 문서를 처리하는 가장 간단한 방법입니다.

$FileZillaServer = simplexml_load_string(
    '<FileZillaServer> 
     <Users> 
      <User Name="test" /> 
     </Users> 
    </FileZillaServer>' 
); 

$User = $FileZillaServer->Users->addChild('User'); 
$User['Name'] = 'Test2'; 

echo $FileZillaServer->asXML(); 
+0

그것은 <사용자 이름 = "Test2를"/> 추가 고지은/"TEST2"후에는 없을 것이다. –

+0

거기에 아주 많이 머물러 있어야합니다. 나는 확신 할 수 있습니다. 그렇지 않으면 XML 형식이 잘못되었습니다. –