DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Output JavaScript Variables From PHP
Class with useful static methods for outputting PHP values into JavaScript format.
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class JS{
//generic and maybe not the desired results xD
function value($o){
if($o === null)
return 'null';
$t = strtolower(gettype($o));
if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer')))
$t = 'number';
elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x')
$t = 'date';
elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1))
$t = 'object';
elseif(!in_array($t, array('boolean', 'string', 'array', 'object')))
$t = 'string';
$t = 'from' . $t;
return self::$t($o);
}
function fromNumber($o){
return +$o . '';
}
function fromObject($o){
$r = array();
foreach($o as $n => $v)
$r[] = self::fromString($n) . ':' . self::value($v);
return '{' . implode(',', $r) . '}';
}
function fromBoolean($o){
return $o ? 'true' : 'false';
}
//$q = should quote?
//$c = char that will be used to quote
function fromString($o, $q = true, $c = '"'){
return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p;
}
function fromArray($o){
$s = '';
foreach($o as $v)
$s .= ($s ? ',' : '') . self::value($v);
return '[' . $s . ']';
}
function fromDate($o){
(is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime());
$o = explode(',', date('Y,n,j,G,i,s', $o));
foreach($o as $i => $v)
$o[$i] = +$v;
return 'new Date(' . implode(',', $o) . ')';
}
}
Example
$o = new stdClass;
$o->abc = 123;
echo implode("\n<br />", array(
JS::value('1984-07-22 11:30:12'),
JS::value('Test'),
JS::value(1234),
JS::value(true),
JS::value(array(1,2,3)),
JS::value(array('lala' => 'x')),
JS::value($o)
));





