Insert the value of a Javascript String into a file

Asked

Viewed 227 times

0

I have the following Javascript code:

// Converts XML to JSON
// from: http://coursesweb.net/javascript/convert-xml-json-javascript_s2
function XMLtoJSON() {
    var me = this; // stores the object instantce

    // gets the content of an xml file and returns it in 
    me.fromFile = function(xml, rstr) {
        // Cretes a instantce of XMLHttpRequest object
        var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        // sets and sends the request for calling "xml"
        xhttp.open("GET", xml, false);
        xhttp.send(null);

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xhttp.responseXML));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // returns XML DOM from string with xml content
    me.fromStr = function(xml, rstr) {
        // for non IE browsers
        if (window.DOMParser) {
            var getxml = new DOMParser();
            var xmlDoc = getxml.parseFromString(xml, "text/xml");
        } else {
            // for Internet Explorer
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
        }

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xmlDoc));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // receives XML DOM object, returns converted JSON object
    var setJsonObj = function(xml) {
        var js_obj = {};
        if (xml.nodeType == 1) {
            if (xml.attributes.length > 0) {
                js_obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    js_obj["@attributes"][attribute.nodeName] = attribute.value;
                }
            }
        } else if (xml.nodeType == 3) {
            js_obj = xml.nodeValue;
        }
        if (xml.hasChildNodes()) {
            for (var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(js_obj[nodeName]) == "undefined") {
                    js_obj[nodeName] = setJsonObj(item);
                } else {
                    if (typeof(js_obj[nodeName].push) == "undefined") {
                        var old = js_obj[nodeName];
                        js_obj[nodeName] = [];
                        js_obj[nodeName].push(old);
                    }
                    js_obj[nodeName].push(setJsonObj(item));
                }
            }
        }
        return js_obj;
    }

    // converts JSON object to string (human readablle).
    // Removes '\t\r\n', rows with multiples '""', multiple empty rows, '  "",', and "  ",; replace empty [] with ""
    var jsontoStr = function(js_obj) {
        var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\\t|\\r|\\n)/g, '').replace(/"",[\n\t\r\s]+""[,]*/g, '').replace(/(\n[\t\s\r]*\n)/g, '').replace(/[\s\t]{2,}""[,]{0,1}/g, '').replace(/"[\s\t]{1,}"[,]{0,1}/g, '').replace(/\[[\t\s]*\]/g, '""');
        return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';
    }
};

// creates object instantce of XMLtoJSON
var xml2json = new XMLtoJSON();

This code is interpreted in my index.html by code:

<body>
    <h4>Result JSON</h4>
    <pre id="jsnstr"></pre>

    <script type="text/javascript" src="xml2json.js"></script>
    <script type="text/javascript">
        // <![CDATA[
        // gets the JSON string from a file with XML content ("test.xml")
        var jsonstr = xml2json.fromFile('arquivo.xml', 'string');

        // adds the JSON string in HTML element with id="jsnstr"
        document.getElementById('jsnstr').innerHTML = jsonstr;
        // ]]>
    </script>
</body>

Someone can tell me a way to insert the "jsnstr" value into a.txt file (where the code will create the file)?
Should I use php for this ? Jquery ?
What’s the simplest way?

1 answer

0

as far as I know it is not possible to write files to the server using javascript only.

You’ll need to create a PHP script that will be responsible for saving the file to the server, such as:

$file = fopen("upload/arquivo.txt", 'w');// Cria um novo arquivo
fwrite($file, $data); // Insere o conteúdo
fclose($file);

From there you could send the content you want to save via Ajax pro PHP script.

I hope I’ve helped.

  • as to create using javascript I already knew, this code you sent me I was testing but unsuccessfully, I used as follows: "<? php $Convert = "<script>Document.write(jsonstr)</script>"; $Myfile = fopen("m_visa.json", "w") or die("Unable to open file!"); $txt = Convert; fwrite($Myfile, $txt); fclose($Myfile); ? >""but it didn’t work or I didn’t know how to do it. How should I make it work via ajax ?

  • You cannot pass the string to PHP using "Document.write". Make a post request via AJAX, passing the string as parameter, to a PHP script that receives it in the $_POST array and then write in file as @Brunom recommended. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.