最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Send JavaScript array using JSON or XML? How to turn it to XML? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Dec 27, 2011 at 21:30 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Apr 19, 2009 at 16:28 Peter PerháčPeter Perháč 20.8k23 gold badges128 silver badges153 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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.

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

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

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

    License: http://creativemons/licenses/LGPL/2.1/
    Version: 0.9
    Author:  Stefan Goessner/2006
    Web:     http://goessner/ 
*/
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.

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 ;)

发布评论

评论列表(0)

  1. 暂无评论