note 72474 added to function.var-dump
| From: | sneskid at hotmail dot com | Date: | Sat, 20 Jan 2007 04:48:38 +0000 |
| Subject: | note 72474 added to function.var-dump | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-121946@lists.php.net to get a copy of this message | ||
Since PHP and Javascript are friends:
<?php
function js_dump($js,$n,$z='') {
if($z) {$a = $z . "['" . $n . "']";}
else {$r = 'var '; $a = $n;}
$r .= $a;
if(is_array($js)) {
$r .= ' = new Array();' . "\r\n";
foreach($js as $k => $v) {
if(is_array($v)) {$r .= js_dump($v, $k, $a);}
else {$r .= $a . "['" . $k . "']" . to_js_safe($v);}
}
}
else {$r .= to_js_safe($js);}
return $r;
}
function to_js_safe($js) {return " = '" . addcslashes($js,"\\'") .
"';\r\n";}
// example:
$arr = array();
$arr['hello'] = 'ba\'\\"by';
$arr['arr2']['h'] = 'zero';
$arr['arr2']['j'] = 'one';
$arr['arr2']['2']['0'] = 'zero';
$arr['arr2']['2']['1'] = 'one';
$arr[123] = 'but avoid these names in method 1';
// method 1
foreach($arr as $k=>$v) $j .= js_dump($v, $k);
//or method 2 (probably a better idea)
//$j = js_dump($arr,'result');
//then:
//$j = 'AJAX=' . rawurlencode($j);
echo $j;
?>
js_dump( variable/array to dump , starter name )
It's not very optimized and I'm no fan of recursion, but for small arrays this works well.
I left 2 "\r\n" in there for readability, you should take them out.
NOTE it doesn't check for numerically named variables.
The result is Javascript eval() friendly.
See this tutorial if you are new to AJAX programming:
http://www.boutell.com/newfaq/creating/ajaxfetch.html
----
Server IP: 69.147.83.197
Probable Submitter: 74.118.123.241
----
Manual Page -- http://www.php.net/manual/en/function.var-dump.php
Edit -- https://master.php.net/note/edit/72474
Del: integrated -- https://master.php.net/note/delete/72474/integrated
Del: useless -- https://master.php.net/note/delete/72474/useless
Del: bad code -- https://master.php.net/note/delete/72474/bad+code
Del: spam -- https://master.php.net/note/delete/72474/spam
Del: non-english -- https://master.php.net/note/delete/72474/non-english
Del: in docs -- https://master.php.net/note/delete/72474/in+docs
Del: other reasons-- https://master.php.net/note/delete/72474
Reject -- https://master.php.net/note/reject/72474
Search -- https://master.php.net/manage/user-notes.php