I need to generate the following script using PHP and json_encode().
var obj= { o1:123, o2: { o3: 456, o4: function() {return $( "#myID" ).val();} } }
My attempt to do so is as follows.
<?php $a=array( 'o1'=>123, 'o2'=>array( 'o3'=>456, 'o4'=>'function() {return $( "#myID" ).val();}' ) ); $json=json_encode($a); ?> <script type="text/javascript"> <?php echo("var obj={$json};");?> console.log(obj); </script>
The resultant output is as follows. The quotes around the properties poses no issues, however, the quotes around the JavaScript renders it as a string and not JavaScript. I obviously can’t not quote the JavaScript in the array as it will result in malformed JSON.
How can I include JavaScript in PHP’s json_encode()?
var obj={ "o1":123, "o2":{ "o3":456, "o4":"function() {return $( "#username" ).val();}" } };
Advertisement
Answer
How about removing the quotations that surround the function?
<?php $obj = array( 'o1' => 123, 'o2' => array( 'o3' => 456, 'o4' => 'function() {return $( "#myID" ).val();}', 'o5' => 'function(param) {return $( "#myID" ).val();}' ) ); $json = json_encode($obj); while ($func = strpos($json, '":"function(')) { $json = substr($json, 0, $func + 2) . substr($json, $func + 3); while ($quote = strpos($json, '"', $func + 2)) { $func = $quote + 1; if (substr($json, $quote - 1, 1) == "\") { $json = substr($json, 0, $quote - 1) . substr($json, $quote); continue; } $json = substr($json, 0, $quote) . substr($json, $quote + 1); break; } } echo $json;
This checks if the string starts with function(
, and if it is, removes the double quotes.
The result is a JSON (but can still be used as a JavaScript object):
{"o1":123,"o2":{"o3":456,"o4":function() {return $( "#myID" ).val();},"o5":function(param) {return $( "#myID" ).val();}}}
Upon setting this object to a variable, you can see that the function registered fine.
With that, you can still use the same technique you used before:
<script type="text/javascript"> <?php echo("var obj={$json};");?> console.log(obj); </script>