1

我有一个文本区域,我在其中打印我的所有 xml,如下所示:

<form method="post" action="">
<textarea id="codeTextarea" name="thisxml" cols="100" rows="36">
<?php
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML('<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
  <game id="103478">
    <opponent>Peter</opponent>
    <oppid>4</oppid>
    <lastdraw>0</lastdraw>
  </game>
  <game id="103479">
    <opponent>Peter</opponent>
    <oppid>4</oppid>
    <lastdraw>2</lastdraw>
  </game>
  <game id="103483">
    <opponent>James</opponent>
    <oppid>47</oppid>
    <lastdraw>2</lastdraw>
  </game>
</data>');

echo htmlspecialchars($xml->saveXML()); 
?>
</textarea>

然后我在提交时想用新的 xml 创建/更新文件,但我在新的 xml 文档中得到的只是:

<?xml version="1.0"?>

我尝试使用 PHP 保存这样的 xml:

$myFile = 'TEST.xml';
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = htmlspecialchars($_POST['thisxml']);
fwrite($fh, $stringData);
fclose($fh);

有人可以告诉我我做错了什么吗?

提前致谢 ;-)

4

3 回答 3

3

使用htmlspecialchars($_POST['thisxml'])会让你XML invalid的回报类似于

&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;data&gt;
  &lt;game id=&quot;103478&quot;&gt;
    &lt;opponent&gt;Peter&lt;/opponent&gt;
    &lt;oppid&gt;4&lt;/oppid&gt;
    &lt;lastdraw&gt;0&lt;/lastdraw&gt;
  &lt;/game&gt;
  &lt;game id=&quot;103479&quot;&gt;
    &lt;opponent&gt;Peter&lt;/opponent&gt;
    &lt;oppid&gt;4&lt;/oppid&gt;
    &lt;lastdraw&gt;2&lt;/lastdraw&gt;
  &lt;/game&gt;
  &lt;game id=&quot;103483&quot;&gt;
    &lt;opponent&gt;James&lt;/opponent&gt;
    &lt;oppid&gt;47&lt;/oppid&gt;
    &lt;lastdraw&gt;2&lt;/lastdraw&gt;
  &lt;/game&gt;
&lt;/data&gt;

只需使用file_put_contents它结合了以下功能fopen , fwrite , fclose

file_put_contents('TEST.xml', $_POST['thisxml']);
于 2012-10-01T16:17:33.430 回答
0

您可以使用以下方法直接保存 XML 文件DOMDocument::save

$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;

if ($xml->loadXML($_POST['thisxml']) === FALSE)
{
    die("The submitted XML is invalid");
}

if ($xml->save('TEST.xml') === FALSE)
{
    die("Can't save file");
}
于 2012-10-01T16:20:42.443 回答
0

我找到了这个脚本并将其添加到标题中,瞧 :-)

function stripslashes_array(&$array, $iterations=0) {
    if ($iterations < 3) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                stripslashes_array($array[$key], $iterations + 1);
            } else {
                $array[$key] = stripslashes($array[$key]);
            }
        }
    }
}

if (get_magic_quotes_gpc()) {
    stripslashes_array($_GET);
    stripslashes_array($_POST);
    stripslashes_array($_COOKIE);
}

感谢您的输入 ;-)

于 2012-10-01T16:39:37.573 回答