dongshanji3102
2014-03-24 12:24
浏览 42

使用JQuery AJAX将XML写入文件

I have to write to an XML file and since the only way I know to do that from JavaScript is using AJAX that's the way I'm trying to achieve so but it's been a while since I last used it and I'm not being able to parse the text so I get HTML codes for characters instead of the characters themselves.

What I have:

AJAX

$.ajax({
    type: 'POST',
    url: "writeXML.php",
    dataType: 'xml',
    data: {filename: "test.xml", content: listXML},
    error: function() {
        alert("Unknown error. Data could not be written to the file.");
    },
    success: function() {
        window.open("test.xml");
    }
});

PHP file

<?php

$fileName = htmlspecialchars($_POST["filename"]);
$content = htmlspecialchars($_POST["content"]);
$file = fopen($fileName, "w");
fwrite($file, $content);
fclose($file);
?>

What I am trying to achieve:

<?xml version="1.0" encoding="UTF-8"?>
<SeriesList>
<Series>
 <title>Ookami to Koushinryou</title>
 <score>6</score>
 <episodes>7</episodes>
 <episodesTotal>23</episodesTotal>
 <episodeLength>20</episodeLength>
 <timesWatched>dropped</timesWatched>
</Series>
<Series>
 <title>Speed Grapher</title>
 <score>5</score>
 <episodes>7</episodes>
 <episodesTotal>24</episodesTotal>
 <episodeLength>20</episodeLength>
 <timesWatched>dropped</timesWatched>
</Series>
</SeriesList>

What I get:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;SeriesList&gt;    
&lt;Series&gt;
 &lt;title&gt;Ookami to Koushinryou&lt;/title&gt;
 &lt;score&gt;6&lt;/score&gt;
 &lt;episodes&gt;7&lt;/episodes&gt;
 &lt;episodesTotal&gt;23&lt;/episodesTotal&gt;
 &lt;episodeLength&gt;20&lt;/episodeLength&gt;
 &lt;timesWatched&gt;dropped&lt;/timesWatched&gt;
&lt;/Series&gt;    
&lt;Series&gt;
 &lt;title&gt;Speed Grapher&lt;/title&gt;
 &lt;score&gt;5&lt;/score&gt;
 &lt;episodes&gt;7&lt;/episodes&gt;
 &lt;episodesTotal&gt;24&lt;/episodesTotal&gt;
 &lt;episodeLength&gt;20&lt;/episodeLength&gt;
 &lt;timesWatched&gt;dropped&lt;/timesWatched&gt;
&lt;/Series&gt;    
&lt;/SeriesList&gt;

So what can I do? I tried utf8_encode() but it did not work and I'm not exactly what you'd call versatile with PHP so I'm out of ideas.

I searched the net for everything I thought of but nothing worked so far.

Thanks in advance for everything.

1条回答 默认 最新

相关推荐 更多相似问题