Jesús Cruz
Jesús Cruz

Reputation: 192

Write XML to file using JQuery AJAX

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.

Upvotes: 0

Views: 2062

Answers (1)

Quentin
Quentin

Reputation: 943193

Remove all your uses of htmlspecialchars.

Your file system doesn't use HTML to express filenames, so you shouldn't convert your filenames to HTML. (You need to sanitise your filename though, at the moment you are letting people overwrite just about any file they like on your server!)

Your XML data is already XML, so you couldn't convert it to an HTML representation of XML.

Upvotes: 1

Related Questions