Use PHP functions in JavaScript

JavaScript var_dump

Dumps a string representation of variable to output

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160
function var_dump () {
    // Dumps a string representation of variable to output  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/var_dump    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Zahlii
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: echo
    // %        note 1: For returning a string, use var_export() with the second argument set to true    // *     example 1: var_dump(1);
    // *     returns 1: 'int(1)'
    var output = '',
        pad_char = ' ',
        pad_val = 4,        lgth = 0,
        i = 0,
        d = this.window.document;
    var _getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    }; 
    var _repeat_char = function (len, pad_char) {
        var str = '';
        for (var i = 0; i < len; i++) {
            str += pad_char;        }
        return str;
    };
    var _getInnerVal = function (val, thick_pad) {
        var ret = '';        if (val === null) {
            ret = 'NULL';
        } else if (typeof val === 'boolean') {
            ret = 'bool(' + val + ')';
        } else if (typeof val === 'string') {            ret = 'string(' + val.length + ') "' + val + '"';
        } else if (typeof val === 'number') {
            if (parseFloat(val) == parseInt(val, 10)) {
                ret = 'int(' + val + ')';
            } else {                ret = 'float(' + val + ')';
            }
        }
        // The remaining are not PHP behavior because these values only exist in this exact form in JavaScript
        else if (typeof val === 'undefined') {            ret = 'undefined';
        } else if (typeof val === 'function') {
            var funcLines = val.toString().split('\n');
            ret = '';
            for (var i = 0, fll = funcLines.length; i < fll; i++) {                ret += (i !== 0 ? '\n' + thick_pad : '') + funcLines[i];
            }
        } else if (val instanceof Date) {
            ret = 'Date(' + val + ')';
        } else if (val instanceof RegExp) {            ret = 'RegExp(' + val + ')';
        } else if (val.nodeName) { // Different than PHP's DOMElement
            switch (val.nodeType) {
            case 1:
                if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') { // Undefined namespace could be plain XML, but namespaceURI not widely supported                    ret = 'HTMLElement("' + val.nodeName + '")';
                } else {
                    ret = 'XML Element("' + val.nodeName + '")';
                }
                break;            case 2:
                ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')';
                break;
            case 3:
                ret = 'TEXT_NODE(' + val.nodeValue + ')';                break;
            case 4:
                ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')';
                break;
            case 5:                ret = 'ENTITY_REFERENCE_NODE';
                break;
            case 6:
                ret = 'ENTITY_NODE';
                break;            case 7:
                ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue + ')';
                break;
            case 8:
                ret = 'COMMENT_NODE(' + val.nodeValue + ')';                break;
            case 9:
                ret = 'DOCUMENT_NODE';
                break;
            case 10:                ret = 'DOCUMENT_TYPE_NODE';
                break;
            case 11:
                ret = 'DOCUMENT_FRAGMENT_NODE';
                break;            case 12:
                ret = 'NOTATION_NODE';
                break;
            }
        }        return ret;
    };
 
    var _formatArray = function (obj, cur_depth, pad_val, pad_char) {
        var someProp = '';        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char);        var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char);
        var str = '';
        var val = '';
 
        if (typeof obj === 'object' && obj !== null) {            if (obj.constructor && _getFuncName(obj.constructor) === 'PHPJS_Resource') {
                return obj.var_dump();
            }
            lgth = 0;
            for (someProp in obj) {                lgth++;
            }
            str += 'array(' + lgth + ') {\n';
            for (var key in obj) {
                var objVal = obj[key];                if (typeof objVal === 'object' && objVal !== null && !(objVal instanceof Date) && !(objVal instanceof RegExp) && !objVal.nodeName) {
                    str += thick_pad + '[' + key + '] =>\n' + thick_pad + _formatArray(objVal, cur_depth + 1, pad_val, pad_char);
                } else {
                    val = _getInnerVal(objVal, thick_pad);
                    str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n';                }
            }
            str += base_pad + '}\n';
        } else {
            str = _getInnerVal(obj, thick_pad);        }
        return str;
    };
 
    output = _formatArray(arguments[0], 0, pad_val, pad_char);    for (i = 1; i < arguments.length; i++) {
        output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char);
    }
 
    if (d.body) {        this.echo(output);
    } else {
        try {
            d = XULDocument; // We're in XUL, so appending as plain text won't work
            this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');        } catch (e) {
            this.echo(output); // Outputting as plain text may work in some plain XML
        }
    }
}
external links: original PHP docs | raw js source

Examples

Running

1
var_dump(1);

Should return

1
'int(1)'

Dependencies

In order to use this function, you also need:

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have var_dump goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
ekim
20 Apr '11 Permalink

q  Can it dump RA or curse defined as :

RA=[]; RA[1]=RA;
curse={re:RA}; curse.s=curse;


?

If so, can the output be posted to see how it's represented?

Gravatar
Brett Zamir
10 Mar '10 Permalink

q  Thanks, Zahlii! I've committed some changes to http://github.com/kvz/phpjs/raw/master/functions/var/var_dump.js . I removed a global, added support for RegExp, cleaned up the function appearance a little and added more support for other DOM node types, and cleaned up. If you want to get a string returned, use var_export() (as in PHP) with the second argument set to true. We don't currently support output buffering.

Gravatar
Zahlii
6 Mar '10 Permalink

q  I changed that .js a bit.
Now it is able to:

* var_dump functions
* var_dump Date(s) as String

function var_dump () {
    var output = "", pad_char = " ", pad_val = 4, lgth = 0, i = 0, d = this.window.document;
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    var repeat_char = function (len, pad_char) {
        var str = "";
        for (var i=0; i < len; i++) {
            str += pad_char;
        }
        return str;
    };
    var getScalarVal = function (val) {
        var ret = '';
        if (val === null) {
            ret = 'NULL';
        }
        else if (typeof val === 'boolean') {
            ret = 'bool('+val+')';
        }
        else if (typeof val === 'string') {
            ret = 'string('+val.length+') "'+val+'"';
        }
        else if (typeof val === 'number') {
            if (parseFloat(val) == parseInt(val, 10)) {
                ret = 'int('+val+')';
            }
            else {
                ret = 'float('+val+')';
            }
        }
        else if (val === undefined) {
            ret = 'UNDEFINED'; // Not PHP behavior, but neither is undefined as value
        }
        else if (typeof val === 'function') {
            ret = 'FUNCTION'; // Not PHP behavior, but neither is function as value
			ret = val.toString().split("\n");
			txt = "";
			for(var j in ret) {
				txt+= (j !=0 ? thick_pad : '')+ret[j]+"\n";
			}
			ret = txt;
        }
		else if(val instanceof Date) {
			val = val.toString();
			ret = 'string('+val.length+') "'+val+'"'
		}
		else if(val.nodeName) {
			ret = 'HTMLElement("'+val.nodeName.toLowerCase()+'")';
		}
        return ret;
    };
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        var someProp = '';
        if (cur_depth > 0) {
            cur_depth++;
        }
        base_pad = repeat_char(pad_val*(cur_depth-1), pad_char);
        thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
        var val='';
        if (typeof obj === 'object' && obj !== null) {
            if (obj.constructor && getFuncName(obj.constructor) === 'PHPJS_Resource') {
                return obj.var_dump();
            }
            lgth = 0;
            for (someProp in obj) {
                lgth++;
            }
            str += "array("+lgth+") {\n";
            for (var key in obj) {
                if (typeof obj[key] === 'object' && obj[key] !== null && !(obj[key] instanceof Date) && !obj[key].nodeName) {
                    str += thick_pad + "["+key+"] =>\n"+thick_pad+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    val = getScalarVal(obj[key]);
                    str += thick_pad + "["+key+"] =>\n"+  thick_pad +val + "\n";
                }
            }
            str += base_pad + "}\n";
        } else {
            str = getScalarVal(obj);
        }
        return str;
    };
    output = formatArray(arguments[0], 0, pad_val, pad_char);
    for (i=1; i < arguments.length; i++) {
        output += '\n'+formatArray(arguments[i], 0, pad_val, pad_char);
    }
	return output;
}

Gravatar
Brett Zamir
24 Feb '10 Permalink

q  @Ben: Can you give the example code you used to test?

Gravatar
Ben
23 Feb '10 Permalink

q  Doesn't seem to work in Chrome, only worked in Firefox :(

Gravatar
joelwallis
3 Aug '09 Permalink

q  Very good idea!


Contribute a New function

More functions

In this category

doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
isset
print_r
serialize
settype
strval
unserialize
» var_dump
var_export

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !