note 69342 deleted from function.json-encode by rquadling

From: Date: Fri, 02 Mar 2007 13:01:58 +0000
Subject: note 69342 deleted from function.json-encode by rquadling
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-124010@lists.php.net to get a copy of this message
Note Submitter: RQuadling at GMail dot com ---- In trying to get an array which contains &, " ' in it into a JS select took me a little while. My solution is a combination of htmlentites() and addslashes(), just like any other sort of data output. The example code takes an array and creates a JS object (as the PHP variable is an associative array). I also use both single and double quotes in the eval statement to prove resilience. See http://rquadling.php1h.com/ for this and other usefull info. <?php // Define array with missing indexes. $a_List = array ( 0 => 'Examine Locks', 1 => 'Get Grade', 2 => 'Get Manufacturer', 3 => "Get Manufacturer's Pattern", // unescaped ' 6 => 'Get Mould Number', 7 => 'Validate A&R', // & will become &amp; 'Quote' => '"The answer is : 42".', // " will becode &quot; 'Last' => 'Quit Process', ); // Make sure any HTML Entities are not sent unescaped. foreach($a_List as $m_Key => $m_Value) { $a_List[$m_Key] = htmlentities($m_Value); } // JSON Encode the list $s_JSON_Encoded = addslashes(json_encode($a_List)); // Get the list into simple variable for printing. $s_List = var_export($a_List, True); // Output the results along with some JS to show what was received. echo <<< END_TEXT <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>JSON test</title> </head> <body> <div>Original Data : <pre>$s_List</pre></div> <div>JSON Encoded : <pre>$s_JSON_Encoded</pre></div> <div>JSON Decoded : <pre><script language="JavaScript" type="text/javascript"> var obj_dq = eval("($s_JSON_Encoded)"); var obj_sq = eval('($s_JSON_Encoded)'); var s_dq = ''; var s_sq = ''; for(var s_label in obj_dq) { s_dq = s_dq + '\\n' + s_label + ' => ' + obj_dq[s_label] + ','; } for(var s_label in obj_sq) { s_sq = s_sq + '\\n' + s_label + ' => ' + obj_sq[s_label] + ','; } document.writeln(s_dq + '\\n' + s_sq); </script></pre></div> </body> </html> END_TEXT; ?>

« previous php.notes (#124010) next »