Development

HowtoInitializeJavascriptWithJson: JsonHelper.php

You must first sign up to be able to contribute.

HowtoInitializeJavascriptWithJson: JsonHelper.php

File JsonHelper.php, 1.3 kB (added by tumf, 11 years ago)

JsonHelper?

Line 
1 <?php
2 /**
3  * JsonHelper
4  *
5  * @package    symfony
6  * @subpackage helper
7  * @author     Yoshihro TAKAHARA <y.takahara@gmail.com>
8  * @version    SVN: $Id$
9  *
10  * 1. install
11  *    Deploy this file to user lib/helper directory
12  *
13  * 2. in action
14  * <code>
15  *    $var = array("apple" => "good" , "orange" => "nice");
16  *    $this->fruits = $var;
17  * </code>
18  *
19  * 3. in template
20  * <code>
21  * <?php use_helper('Json') ?>
22  *
23  * <php echo export_js("fruits",$fruits) ?>
24  * </code>
25  *
26  * 4. results
27  * <code>
28  * <script type="text/javascript">
29  * //<![CDATA[
30  * var param = {"apple":"good","orange":"nice"} ;
31  * //]]>
32  * </script>
33  * </code>
34  *
35  */
36 use_helper("Javascript");
37 function export_js($name,$var){
38     // if $var is escaped. convert to array;
39     if($var instanceof sfOutputEscaperArrayDecorator){
40         $var = iterator_to_array($var);
41     }
42
43     $js = "undefined";
44     // choice json_encode engine
45     // 1. php-json
46     //    http://www.aurore.net/projects/php-json/
47     // 2. PEAR/JSON
48     //    http://mike.teczno.com/json.html
49     if (extension_loaded('json')) {
50         $js = json_encode($var);
51     }else{
52         @require_once('PEAR.php');
53         @require_once('JSON.php');
54         $json = new Services_JSON();
55         @$js = $json->encode($var);
56     }
57     $code = sprintf("var %s = %s ;",$name,$js);
58     return javascript_tag($code);
59
60 }
61 ?>
62