PHP Classes
Icontem

File: class_arraytojs.php


  Search   All class groups All class groups   Latest entries Latest entries   Top 10 charts Top 10 charts   Newsletter Newsletter   Blog Blog   Forums Forums   Help FAQ Help FAQ  
  Login   Register  
Recommend this page to a friend! ReTweet ReTweet Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of Jan Paepke  >  PHP Array to Javascript  >  class_arraytojs.php  
File: class_arraytojs.php
Role: Class source
Content type: text/plain
Description: Main Class File
Class: PHP Array to Javascript
Convert PHP arrays into Javascript objects
 

Contents

Class file image Download
<?
class array_to_js {
    var 
$js_arrays;
    function 
error ($message$stop true) {
        echo 
"<b>array_to_js</b> - FATAL ERROR: ".$message;
        if (
$stop) exit;
    }
    function 
add_array($myarray$outputvarname$level 0) {
        if (isset(
$this->js_arrays[$outputvarname]))
            
$this->error('This Array has been added more than once: "'.$outputvarname.'"');
        for (
$i=0$i<$level$i++) $pre .= '    ';
        
$this->js_arrays[$outputvarname] .= $pre.$outputvarname.' = new Object();'."\n";
        foreach (
$myarray as $key => $value) {
            if (!
is_int($key))
                
$key '"'.addslashes($key).'"';
            if (
is_array($value))
                
$this->add_array($value$outputvarname.'['.$key.']'$level+1);
            else {
                
$this->js_arrays[$outputvarname] .= $pre.'    '.$outputvarname.'['.$key.']'.' = ';

                if (
is_int($value) or is_float($value))
                    
$this->js_arrays[$outputvarname] .= $value;
                elseif (
is_bool($value))
                    
$this->js_arrays[$outputvarname] .= $value "true" "false";
                elseif (
is_string($value))
                    
$this->js_arrays[$outputvarname] .= '"'.addslashes($value).'"';
                else
                    
$this->error('Unknown Datatype for "'.$outputvarname.'['.$key.']"');
                
$this->js_arrays[$outputvarname] .= ";\n";
            }
        }
    }
    function 
output_all($scripttag true) {
        if (
$scripttag$outputstring '<script language="JavaScript" type="text/javascript">'."\n";
        foreach (
$this->js_arrays as $array)
            
$outputstring .= $array;
        if (
$scripttag$outputstring .= '</script>'."\n";

        return 
$outputstring;
    }
}
?>

 
  Advertise on this site Advertise on this site   Site map Site map   Statistics Statistics   Site tips Site tips   Privacy policy Privacy policy   Contact Contact  

For more information send a message to :
info at phpclasses dot org.
Copyright (c) Icontem 1999-2009 PHP Classes - PHP Class Scripts
  PHP Book Reviews - Reviews of books and other products