PHP脚本保存xml不更新


PHP script saves xml without updates

这个脚本使用原始数据创建一个新的XML文件,并且没有更新。

<?php
$dom = new DOMDocument();
$dom->load('communities.xml');
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 
// get document element  
$root   = $dom->documentElement;  
$name     = $dom->createElement("NAME");  
$nameText = $dom->createTextNode("Hobbies");  
$name->appendChild($nameText); 
$community = $dom->createElement('COMMUNITY');
$community->appendChild($name);  
$dom->save('communities.xml');
$tidy_options = array(
                'input-xml'    => true,
                'output-xml'   => true,
                'indent'       => true,
                'wrap'         => false,
        );
$tidy = new tidy();
$tidy->parseFile('communities.xml', $tidy_options);
$tidy->cleanRepair();
echo $tidy;
return;
?>

权限是正确的,因为文件格式被修改了,文件保存了一个新的日期

看起来您缺少一些追加语句,即:

$root->appendChild($name);
...
$root->appendChild($community);

文件可能被修改并有一个新的日期,但是您正在执行两个保存操作,并且可能只有整洁的操作实际上在做任何事情。试一试:

if ($dom->save('communites.xml') === FALSE) {
    die(libxml_get_errors());
}

将输出所有DOM错误

创建元素后,必须将它们添加到文档中:

$community = $dom->createElement('COMMUNITY');
$root->appendChild($community);