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-10 of 11 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)
));

Simple JSON formatting example

// Simple JSON formatting example

({

	'google' : {
	
		'action': 'http://www.google.com.au/search',
		
		'method': 'POST',		
		
		'input': [
		
			'<input type="hidden" value="en" name="hl"/>',
			
			'<input value="" title="Google Search" size="55" name="q" maxlength="2048"/>',
			
			'<input type="hidden" value="en" name="hl"/>'
		
		],
		
		'buttons': [
		
			'<input type="submit" value="Google Search" name="btnG"/>',
			
			'<input type="submit" value="I\'m Feeling Lucky" name="btnI"/>'
		
		],
		
		'image': 'http://www.google.com/intl/en_ALL/images/logo.gif'
		
	},
	
	'yahoo' : {
	
		'action': 'http://search.yahoo.com/search',
		
		'method': 'POST',		
		
		'input': [
		
			'<input value="" maxlength="255" name="q" id="search" type="text">'
		
		],
		
		'buttons': [
		
			'<input value="Search" type="submit">'
		
		],
		
		'image': 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif'		
		
	},	

	'wikipedia' : {
	
		'action': 'http://en.wikipedia.org/wiki/Special:Search',
		
		'method': 'POST',
		
		'input': [
		
			'<input value="" name="search" type="text">'
		
		],
		
		'buttons': [
		
			'<input value="Search" name="go" type="submit">'
		
		],
		
		'image': 'http://en.wikipedia.org/images/wiki-en.png'		
		
	},	

	'imdb' : {
	
		'action': 'http://imdb.com/find',
		
		'method': 'POST',
		
		'input': [
		
			'<input value="" name="q">'
		
		],
		
		'buttons': [
		
			'<input value="Search" type="submit">'
		
		],
		
		'image': 'http://i.media-imdb.com/images/nb15/logo2.gif'		
		
	},	

	'ebay' : {
	
		'action': 'http://search.ebay.com.au/search/search.dll',
		
		'method': 'GET',
		
		'input': [
		
			'<input value="R40" name="from" type="hidden">',
			
			'<input name="satitle" maxlength="300" type="text">'
		
		],
		
		'buttons': [
		
			'<input value="Search" type="submit">'
		
		],
		
		'image': 'http://pics.ebaystatic.com/aw/pics/logos/logoEbay_x45.gif'		
		
	},		
	
	'dictionary' : {
	
		'action': 'http://dictionary.com/search',
		
		'method': 'GET',
		
		'input': [
		
			'<input maxlength="256" value="" name="q" type="text">'
		
		],
		
		'buttons': [
		
			'<input value="Search" type="submit">'
		
		],
		
		'image': 'http://cache.lexico.com/g/d/dictionary_logo.gif'		
		
	},	

	'iboogie' : {
	
		'action': 'http://www.iboogie.com/searchtree.asp',
		
		'method': 'GET',
		
		'input': [
		
			'<input type="text" value="test" name="name_query" />'
		
		],
		
		'buttons': [
		
			'<input type="submit" value=" Search " class="button"/>'
		
		],
		
		'image': 'http://www.iboogie.com/images/iboogie_us.jpg'		
		
	},		
	
})


hCard to JSON bridge

// Requires http://pear.php.net/pepr/pepr-proposal-show.php?id=198 and http://allinthehead.com/hkit
// Many thanks to the authors of these libraries and to the microformats community.
// Demo: http://simplelogica.net/cajondesastre/hcard2json/index.php?url=http://11870.com/pro/19483
// Manuel González Noriega for Simplelógica. Hire us at http://simplelogica.net


    include('hkit.class.php');
    include('JSON.class.php');
		
    $debug = true;
		
    $status = '200';
    $ct = 'text/plain';
		
    $hKit = new hKit;
    $json = new Services_JSON();

    if ($_GET['url']) {
      $result = $hKit->getByURL('hcard', $_GET['url']);
	    
      if ($result) {
	$o = ($json->encode($result));
	$ct = ($debug) ? 'text/plain' : 'application/json';			
      }
      else {
	$o = '404 Not Found';
	$status = '404';
      }
    }
    else {
      $o = '400 Bad Request';
      $status = '400';
    }
	
 

  header('Content-type: '.$ct);
  
  switch($status) {
    case '400':
      header("HTTP/1.0 400 Bad Request");
    break;
	
    case '404':
      header("HTTP/1.0 404 Not Found");
    break;

    case '200':
    default:
      header("HTTP/1.0 200 OK");
    break;
}

print $o;

Pass JSON to Flash's ExternalInterface

var json : String =
	"{a: 1, b: 'hello world', c: [1, 3, 4, 5]}";

var o : Object =
	ExternalInterface.call("function(){return " + json + ";"}");


The variable o should now contain an object representation of the string json.
Stolen from http://blog.iconara.net/2007/01/20/parsing-json-using-externalinterface/

Quick and Dirty JSON Serializer

// quick and dirty JOSN serializer

def jsonize(d)
  def surround(d, i=0); '' << '"[{'[i] << d << '"]}'[i]; end
  alias j jsonize; alias s surround
  if d.kind_of?(String) then s(d)
  elsif d.kind_of?(Symbol) then s(d.to_s)
  elsif d.kind_of?(Array) then s(d.collect {|v| j(v)}.join(', '), 1)
  elsif d.kind_of?(Hash) then s(d.to_a.collect { |v| "#{j(v[0])} : #{j(v[1])}" }.join(', '),2)
  # add support for other types of objects here if needed...
  else d.to_s; end
end

Broadcasting DZONE Shares

// This snippet will allow you to show your DZONE shares
// on your web page. Visit your shares page, click on the "feed" link
// to get the URL of your personal shares feed then paste it in the first line
// in the script.

var sharedURL='';  // Place your url between the quotes.

function getFeed(url, callback) {
   var newScript = document.createElement('script');
       newScript.type = 'text/javascript';
       newScript.src = 'http://pipes.yahoo.com/pipes/9oyONQzA2xGOkM4FqGIyXQ/run?&_render=JSON&_callback='+callback+'&feed=' + sharedURL;
   document.getElementsByTagName("head")[0].appendChild(newScript);
}

function dzone(feed) {
   var tmp='';
   for (var i=0; i<feed.value.items.length; i++) {
      tmp+='<a href="'+feed.value.items[i].link+'" rel="nofollow">';
      tmp+=feed.value.items[i].title+'</a><br>';
   }
   document.getElementById('dzoneLinks').innerHTML=tmp;
}

getFeed(sharedURL, 'dzone');


// Paste that code at the end of your page. In your HTML place the following two divisions
// where you would like your feed to appear. (feel free to style the divisions however you wish)
// you can add to/subtract from the outer division but the inner division will always be overwritten
// with your shares.

<div id='dzoneLayer'>
My DZONE Recommendations
   <div id='dzoneLinks'>
   </div>
</div>

JSON Parser in Haskell

I've been having trouble writing parsers recently, and I've been meaning to get to grips with Haskell at some point, so I figured I'd write a simple JSON parser using Haskell's Parsec library. Here's the code for it:

Update: I've modified this to use Data.Map instead of a list of key value pairs for the record / object implementation. I've also removed the 'identifier' feature as it isn't really part of JSON proper. Also, I've noticed that this seems to have acquired some sort of presence on google. This isn't really very good code - it's more a demonstration of parsec than it is an actually useful parser. (I mean, it works fine, and it's probably sufficient for trivial uses, but I wouldn't e.g. guarantee it to be bug free). I strongly recommend using this one instead.

import Text.ParserCombinators.Parsec
import System
import qualified Data.Map as Map

-- Main method. Currently not very interesting - just a test piece of code which accepts
-- a file and prints out a representation of the parsed type (or an error message if it is
-- invalid.
mainParser = do {
    val <- valueParser
    ; skipMany space
    ; eof
    ; return val }

main :: IO ()
main = do {
    args <- getArgs 
  ; val <- parseFromFile mainParser $ args !! 0 
  ; print(val) } 

-- Matches string literals. 
literalString :: Parser JSON 
literalString = do {
        char '"'
      ;  val <-  many1 letter
      ;  char '"'
      ; return $ LiteralString val}


-- Data type representing a JSON AST. Roughly corresponds to a Javascript object.
data JSON = ListValue [JSON] 
          | LiteralString String
          | LiteralInt Integer
          | LiteralBoolean Bool
          | RecordValue (Map.Map String JSON)
            deriving Show         


-- Combined parser.
valueParser :: Parser JSON
valueParser =       
        literalString
    <|> literalInt
    <|> literalBoolean
    <|> recordParser
    <|> listParser 

-- Matches literal integers.
literalInt :: Parser JSON
literalInt = do {
    ; val <- many1 digit
    ; return $ LiteralInt (read val)
        }

-- Matches boolean literals
literalBoolean :: Parser JSON
literalBoolean =
                do{ 
                  string "true"
                ; return $ LiteralBoolean True}
            <|> do{
                  string "false"
                ; return $ LiteralBoolean False}

-- Code for parsing lists.
-- Matches comma separated lists enclosed in [ ]
listParser :: Parser JSON 
listParser = do{ 
                char '['
              ; words <- sepBy1 valueParser listSeparator
              ; char ']'
              ; return $ ListValue words
              }

-- Matches ',' with any amount of space on either side.
listSeparator :: Parser ()
listSeparator = do{ 
      skipMany space 
    ; char ','
    ; skipMany space
}

-- Code for parsing records.
-- Matches { word : JSON; word : JSON; word : value; ... }
recordParser :: Parser JSON 
recordParser = do{
      char '{'
    ; defs <- endBy definitionParser definitionSeparator
    ; char '}'
    ; return $ RecordValue $ Map.fromList defs 
}

-- Matches things of the form word : JSON
definitionParser :: Parser (String, JSON)
definitionParser = do{
      skipMany space
    ; key <- many1 letter 
    ; skipMany space
    ; char ':'
    ; skipMany space
    ; val <- valueParser
    ; return (key, val)
}

-- Matches ';' with any amount of space on either side.
definitionSeparator :: Parser ()
definitionSeparator = do {
      skipMany space
    ; char ';'
    ; skipMany space
    ; return () 
}


Associate array to XML and JSON

PHP Associate array data

$data = array(
    "hoge" => 123,
    "foo" => 456,
    "bar" => 789,
    "aaa" => array(
        "abc" => 111,
        "bcd" => 222,
        "cde" => 333
    ),
    "bbb" => array(
        "def" => array(
            "efg" => "hoge"
        )
    )
);


to XML

$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('root');

function write(XMLWriter $xml, $data){
    foreach($data as $key => $value){
        if(is_array($value)){
            $xml->startElement($key);
            write($xml, $value);
            $xml->endElement();
            continue;
        }
        $xml->writeElement($key, $value);
    }
}
write($xml, $data);

$xml->endElement();
echo $xml->outputMemory(true);


output XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <hoge>123</hoge>
    <foo>456</foo>
    <bar>789</bar>
    <aaa>
        <abc>111</abc>
        <bcd>222</bcd>
        <cde>333</cde>
    </aaa>
    <bbb>
        <def>
            <efg>hoge</efg>
        </def>
    </bbb>
</root>


to JSON

echo json_encode($data);


output JSON
{
    "hoge":123,
    "foo":456,
    "bar":789,
    "aaa":{
        "abc":111,
        "bcd":222,
        "cde":333
    },
    "bbb":{
        "def":{
            "efg":"hoge"
        }
    }
}


Requires PHP5.2.x or xmlwriter extension, json extension

Active Record to_hash

With this mix-in, you can have nice "to_hash" methods on your active record objects.

I find it good for programming JSON apps.

In lib/ar_hashing.rb
module ActiveRecordHashing
  def to_hash
      Hash[*self.map{ |m| [m.id, m]}.flatten]               
  end
end


and in config/environment.rb
require 'ar_hashing'

class ActiveRecord::Associations::AssociationCollection
  include ActiveRecordHashing
end

Simple JSON and deep clone

Object.prototype.deep_clone = function(){
	eval("var tmp = " + this.toJSON());
	return tmp;
}
Object.prototype.toJSON = function(){
	var json = [];
	for(var i in this){
		if(!this.hasOwnProperty(i)) continue;
		//if(typeof this[i] == "function") continue;
		json.push(
			i.toJSON() + " : " +
			((this[i] != null) ? this[i].toJSON() : "null")
		)
	}
	return "{\n " + json.join(",\n ") + "\n}";
}
Array.prototype.toJSON = function(){
	for(var i=0,json=[];i<this.length;i++)
		json[i] = (this[i] != null) ? this[i].toJSON() : "null";
	return "["+json.join(", ")+"]"
}

String.prototype.toJSON = function(){
	return '"' +
		this.replace(/(\\|\")/g,"\\$1")
		.replace(/\n|\r|\t/g,function(){
			var a = arguments[0];
			return  (a == '\n') ? '\\n':
					(a == '\r') ? '\\r':
					(a == '\t') ? '\\t': ""
		}) +
		'"'
}
Boolean.prototype.toJSON = function(){return this}
Function.prototype.toJSON = function(){return this}
Number.prototype.toJSON = function(){return this}
RegExp.prototype.toJSON = function(){return this}

// strict but slow
String.prototype.toJSON = function(){
	var tmp = this.split("");
	for(var i=0;i<tmp.length;i++){
		var c = tmp[i];
		(c >= ' ') ?
			(c == '\\') ? (tmp[i] = '\\\\'):
			(c == '"')  ? (tmp[i] = '\\"' ): 0 :
		(tmp[i] = 
			(c == '\n') ? '\\n' :
			(c == '\r') ? '\\r' :
			(c == '\t') ? '\\t' :
			(c == '\b') ? '\\b' :
			(c == '\f') ? '\\f' :
			(c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16)))
		)
	}
	return '"' + tmp.join("") + '"';
}


var json = {
 str : "abcde",
 num : 6,
 reg : /foobar/i,
 array : [1,2,3,4,5],
 func : function(x,y){return x+y},
 obj : {a : "b"}
}.toJSON();

alert(json);
// result
{
 "str" : "abcde",
 "num" : 6,
 "reg" : /foobar/i,
 "array" : [1, 2, 3, 4, 5],
 "func" : function(x,y){return x+y},
 "obj" : {
 "a" : "b"
}
}
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS