views:

1839

answers:

4

Okay, my situation is such: I need to send the contents of a JavaScript array to server where a PHP script will persist individual array entries in a MYSQL database. I am NOT using jQuery but I am about to integrate Prototype framework into my project.

I gather that the JS array can easily be converted to JSON using the toJSON() method provided by Prototype. I could then POST this to my script which would somehow de-JSONise the array and insert the values into DB.

But what I am also interested in is NOT using JSON data-interchange format, but converting the JS array into XML, which can be very easily parsed by the simplexml PHP extension (save myself some development time server-side). My question(s) are thus: should I go for JSON or XML? and How could I turn the JS array into XML? (is there a toXML() method like there is toJSON() in Prototype?)

I am aware of the great variety of very similar questions, but they all seem to ask this question the other way around... converting JSON to JS arrays, and many are jQuery related. So please help me, even if this is potentially a duplicate and you may have answered this some place else.

+1  A: 

After using toJSON(), you could use this to convert JSON to XML, from goessner.net (source file):

/*  This work is licensed under Creative Commons GNU LGPL License.

    License: http://creativecommons.org/licenses/LGPL/2.1/
    Version: 0.9
    Author:  Stefan Goessner/2006
    Web:     http://goessner.net/ 
*/
function json2xml(o, tab) {
   var toXml = function(v, name, ind) {
      var xml = "";
      if (v instanceof Array) {
         for (var i=0, n=v.length; i<n; i++)
            xml += ind + toXml(v[i], name, ind+"\t") + "\n";
      }
      else if (typeof(v) == "object") {
         var hasChild = false;
         xml += ind + "<" + name;
         for (var m in v) {
            if (m.charAt(0) == "@")
               xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
            else
               hasChild = true;
         }
         xml += hasChild ? ">" : "/>";
         if (hasChild) {
            for (var m in v) {
               if (m == "#text")
                  xml += v[m];
               else if (m == "#cdata")
                  xml += "<![CDATA[" + v[m] + "]]>";
               else if (m.charAt(0) != "@")
                  xml += toXml(v[m], m, ind+"\t");
            }
            xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
         }
      }
      else {
         xml += ind + "<" + name + ">" + v.toString() +  "</" + name + ">";
      }
      return xml;
   }, xml="";
   for (var m in o)
      xml += toXml(o[m], m, "");
   return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}

That said, I'd personally go for JSON.

InsDel
this looks a bit... cumbersome. To first convert to JSON and then to XML... I like the simplicity of JSON and I would prefer to go for JSON, like you said. On a scale 0..10 how complicated will the situation be at the PHP front? If I passed it JSON, could I turn the JSONised objects to PHP objects as easily as I can parse XML with simplexml?
Peter Perháč
Yes, quite cumbersome it is. But it (should) work. Also, I just found http://us.php.net/json_decode which may be of interest.
InsDel
thanks. Another user just pointed me in that direction too. Seems to be pretty straightforward. I guess I'll avoid XML in my case :)
Peter Perháč
+4  A: 

You have tried the php_json extension methods? Using them you will be able to turn the JSON object into a PHP Object.

From there you can do whatever you want. Make an XML string to process with SimpleXML or persist to the DataStore.

andreas
okay, this sounds good. So you'd recommend JSON for transmitting the JS array?
Peter Perháč
I have never tried these extensions but obviously my server has them enabled and I will give it a go. Thanks!
Peter Perháč
I would say that you can use JSON for transmitting and json_encode(), json_decode() on the server side to transform the JSON message into a PHP variable/object. Give it a try.
andreas
+2  A: 

Hi Masterpeter,

You'll truly save development time if you use php's built-in json_decode

Evert
A: 

I suggest using a native query string which will eliminate all the convertion process. Here is the code which will do the appropriate conversion:

/**
 * This function serializes the object to a standart URI query string which can directly interpreted by PHP.
 * 
 * @param {String} [format] The desired format for the output. Not needed for most usages.
 * @return {String} The URI query string.
  */
Object.prototype.toQueryString=function(format, encodeURI)
{
    if (typeof format!='string')
     format='%s';
    var result='';
    for (var paramName in this) 
    {
     if (this.constructor==Array && isNaN(parseInt(paramName)) || !this.hasOwnProperty(paramName))
      continue;

     if (this[paramName].constructor==Object || this[paramName].constructor==Array)
      result += '&' + this[paramName].toQueryString(format.format(paramName) + '[%s]', encodeURI);
     else
      result += '&' + format.format(paramName) + '=' + ((encodeURI!==false)?encodeURIComponent(this[paramName]):this[paramName]);
    }
    return result.substr(1);
};

Some may not like using Object.prototype. If you are one of them you can change the function to serve as a seperate function easly. If need help, just knock me ;)

BYK