Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

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

Setting a string variable with a mult-line text value

This example demonstrates how easy it is to copy and paste human-readable text from elsewhere and declare it as a string in your code.

string = <<RUBY_RUBY_RUBY
  <mydoc>
    <someelement attribute="nanoo">Text, text, text</someelement>
  </mydoc>
RUBY_RUBY_RUBY



Note: Remember to encase the text within a pair of strings, any string (the convention is to make it uppercase) and ensure it's not a reserved keyword, or a variable declared already.

JavaScript var_dump (Mark 2)

Same as var_dump for PHP, but for JavaScript. Useful if you do not have Firebug.

A typical useage:

document.write(var_dump(ANY-JS-VAR,'html'));

     function var_dump(data,addwhitespace,safety,level) {
        var rtrn = '';
        var dt,it,spaces = '';
        if(!level) {level = 1;}
        for(var i=0; i<level; i++) {
           spaces += '   ';
        }//end for i<level
        if(typeof(data) != 'object') {
           dt = data;
           if(typeof(data) == 'string') {
              if(addwhitespace == 'html') {
                 dt = dt.replace(/&/g,'&amp;');
                 dt = dt.replace(/>/g,'&gt;');
                 dt = dt.replace(/</g,'&lt;');
              }//end if addwhitespace == html
              dt = dt.replace(/\"/g,'\"');
              dt = '"' + dt + '"';
           }//end if typeof == string
           if(typeof(data) == 'function' && addwhitespace) {
              dt = new String(dt).replace(/\n/g,"\n"+spaces);
              if(addwhitespace == 'html') {
                 dt = dt.replace(/&/g,'&amp;');
                 dt = dt.replace(/>/g,'&gt;');
                 dt = dt.replace(/</g,'&lt;');
              }//end if addwhitespace == html
           }//end if typeof == function
           if(typeof(data) == 'undefined') {
              dt = 'undefined';
           }//end if typeof == undefined
           if(addwhitespace == 'html') {
              if(typeof(dt) != 'string') {
                 dt = new String(dt);
              }//end typeof != string
              dt = dt.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
           }//end if addwhitespace == html
           return dt;
        }//end if typeof != object && != array
        for (var x in data) {
           if(safety && (level > safety)) {
              dt = '*RECURSION*';
           } else {
              try {
                 dt = var_dump(data[x],addwhitespace,safety,level+1);
              } catch (e) {continue;}
           }//end if-else level > safety
           it = var_dump(x,addwhitespace,safety,level+1);
           rtrn += it + ':' + dt + ',';
           if(addwhitespace) {
              rtrn += '\n'+spaces;
           }//end if addwhitespace
        }//end for...in
        if(addwhitespace) {
           rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
        } else {
           rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
        }//end if-else addwhitespace
        if(addwhitespace == 'html') {
           rtrn = rtrn.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
        }//end if addwhitespace == html
        return rtrn;
     }//end function var_dump

PHP variable check

ugh

$page = isset($_GET['page']) ? $_GET['page'] : 'home';

Python - Simple Example CGI

// http://localhost/cgi-bin/example.py?variable=example

import cgi

print 'Content-type: text/html\r\n'

inputValue = cgi.FieldStorage()

if(inputValue.has_key('variable')):
  print inputValue['variable'].value

Ruby - Trace Variable Global

// Tracciare variabili Globali

trace_var:$variabileGlobale, proc{ print "variabileGlobale modificata al valore --> ", $variabileGlobale, " "}

parameterized instance variables

// useful when you want to obtain more than one instance of the same type of variable on the
// same page. i.e. two different addresses. credit goes to argv[0] in #rubyonrails on freenode

instance_variable_get("@#{address_type}_address").country.name

var_dump for javascript

hackish implementation of the php 'var_dump()' in javascript:

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}//end function var_dump

change integer variables content

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

#include<stdio.h>
#include<conio.h>
void main(){
	int a, b;
	clrscr();

	printf( "Digite a= " );
	scanf( "%d", &a );

	printf( "Digite b= " );
	scanf( "%d", &b );

	a = b - a + ( b = a );

	printf( "a= %d\nb= %d", a, b);
	getch();
}

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS