-1

HTML フォームに基づいて XML ファイルを出力するコードを作成しましたが、出力形式は次のような単なる長い文字列です。

<?xml version="1.0"?>
<students>
<student><name>Joey Lowery</name><email>jlowery@idest.com</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>jlowery@idest.com</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'); 
}
4

1 に答える 1

2

Try the saveXML() method instead.

Update:

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

Update 2:

See the manual, specifically the comment from devin. He states you should put preserveWhitespace BEFORE the load (as the link Rolando Isidoro gave also states).

$doc = new DOMDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->load('data.xml');
$doc->formatOutput = true;
file_put_contents('test.xml', $doc->saveXML());
于 2013-07-12T17:02:01.677 に答える