2013-07-12 103 views
-1

我有我的代码工作,输出基于HTML表单上的XML文件,但输出格式仅仅是一个长的字符串是这样的:格式化XML输出文件

<?xml version="1.0"?> 
<students> 
<student><name>Joey Lowery</name><email>[email protected]</email><cell>555-555-5555</cell><dob>1999-03-31</dob><study>8</study></student></students> 

,而不是这样的:

<?xml version="1.0"?> 
<students> 
    <student> 
    <name>Joey Lowery</name> 
    <email>[email protected]</email> 
    <cell>555-555-5555</cell> 
    <dob>1999-03-31</dob> 
    <study>8</study> 
    </student> 
</students> 

我使用formatOutput = true以及preserveWhiteSpace = false,但它不起作用。以下是我的代码:

if(isset($_POST['submit'])) { 
$file = "data.xml"; 
$userNode = 'student'; 

$doc = new DOMDocument('1.0'); 
$doc->load($file); 
$doc->preserveWhiteSpace = true; 
$doc->formatOutput = true; 

$root = $doc->documentElement; 

$post = $_POST; 
unset($post['submit']); 

$user = $doc->createElement($userNode); 
$user = $root->appendChild($user); 

foreach ($post as $key => $value) { 
    $node = $doc->createElement($key, $value); 
    $user->appendChild($node); 
} 
$doc->save($file) or die("Error"); 
header('Location: thanks.php'); 
} 
+2

检查此答案:http://stackoverflow.com/questions/3616540/format-xml-string/3616722#3616722。 –

+0

我试图将它保存到一个文件,并且该答案似乎不适用。尽管如此,感谢您的尝试。 –

回答

2

请尝试使用saveXML()方法。

更新:

file_put_contents($file, $doc->saveXML()); 

更新2:

manual,特别是从德文注释。他说你应该在load之前加上preserveWhitespace(正如Rolando Isidoro给出的链接)。

$doc = new DOMDocument('1.0'); 
$doc->preserveWhiteSpace = false; 
$doc->load('data.xml'); 
$doc->formatOutput = true; 
file_put_contents('test.xml', $doc->saveXML()); 
+0

你能更明确吗?我试图在将文件另存为文件之前添加'$ doc = saveXML();'但不行。 –

+0

我也试过$ test1 = $ doc-> saveXML(); - 但再一次,没有爱。我究竟做错了什么? –

+0

saveXML输出一个字符串,你需要存储和保存,例如'file_put_contents()' – pritaeas