This may help others who are seeing null strings returned by json_encode().
This function will encode all array values to utf8 so they are safe for json_encode();
usage:
<?php
json_encode(utf8json($dataArray));
function utf8json($inArray) {
static $depth = 0;
/* our return object */
$newArray = array();
/* safety recursion limit */
$depth ++;
if($depth >= '30') {
return false;
}
/* step through inArray */
foreach($inArray as $key=>$val) {
if(is_array($val)) {
/* recurse on array elements */
$newArray[$key] = utf8json($val);
} else {
/* encode string values */
$newArray[$key] = utf8_encode($val);
}
}
/* return utf8 encoded array */
return $newArray;
}
?>
[NOTE BY danbrown AT php DOT net: Includes a bugfix by (robbiz233 AT hotmail DOT com) on 18-SEP-2010, to replace:
$newArray[$key] = utf8json($inArray);
with:
$newArray[$key] = utf8json($val);"
in the given function.]
json_encode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_encode — Returns the JSON representation of a value
Description
Returns a string containing the JSON representation of value.
Parameters
- value
-
The value being encoded. Can be any type except a resource.
This function only works with UTF-8 encoded data.
- options
-
Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT.
Return Values
Returns a JSON encoded string on success.
Changelog
| Version | Description |
|---|---|
| 5.3.0 | The options parameter was added. |
| 5.2.1 | Added support to JSON encode basic types. |
Examples
Example #1 A json_encode() example
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Example #2 A json_encode() example showing all the options in action
<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&');
echo "Normal: ", json_encode($a), "\n";
echo "Tags: ", json_encode($a,JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a,JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($a,JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a,JSON_HEX_AMP), "\n";
echo "All: ", json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";
$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
?>
The above example will output:
Normal: ["<foo>","'bar'","\"baz\"","&blong&"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026"]
Empty array output as array: []
Empty array output as object: {}
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
json_encode
Dave - s10sys.com
09-Sep-2010 05:46
09-Sep-2010 05:46
nicolas dot baptiste at gmail dot com
18-Aug-2010 05:49
18-Aug-2010 05:49
Beware of index arrays :
<?php
echo json_encode(array("test","test","test"));
echo json_encode(array(0=>"test",3=>"test",7=>"test"));
?>
Will give :
["test","test","test"]
{"0":"test","3":"test","7":"test"}
arrays are returned only if you don't define index.
gansbrest
06-Aug-2010 09:42
06-Aug-2010 09:42
If you have problems with quotes when encoding numeric data retrieved from the database, you can just cast that value to integer and there will be no quotes:
<?php
$testArr['key'] = '1';
print json_encode($testArr);
?>
===> {"key":"1"}
<?php
$testArr['key'] = (int)'1';
print json_encode($testArr);
?>
===> {"key":1}
Don't forget that you have to deal with numbers, otherwise your string will be converted to 0.
Arne Bech
20-Jul-2010 09:00
20-Jul-2010 09:00
To battle the quoting of numbers when encoding data retrieved from mysql you could do a simple preg_replace() to remove the quotes on numbers.
This has worked for me:
<?php
$json = json_encode($dataFromMysql);
$json = preg_replace('/"(-?\d+\.?\d*)"/', '$1', $json);
?>
mic dot sumner at gmail dot com
02-Jul-2010 03:39
02-Jul-2010 03:39
Hey everyone,
In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects.
I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own:
You can place these methods in each of your classes, or put them in a base class, as I've done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access)
<?php
abstract class Model {
public function toArray() {
return $this->processArray(get_object_vars($this));
}
private function processArray($array) {
foreach($array as $key => $value) {
if (is_object($value)) {
$array[$key] = $value->toArray();
}
if (is_array($value)) {
$array[$key] = $this->processArray($value);
}
}
// If the property isn't an object or array, leave it untouched
return $array;
}
public function __toString() {
return json_encode($this->toArray());
}
}
?>
Externally, you can just call
<?php
echo $theObject;
//or
echo json_encode($theObject->toArray());
?>
And you'll get the json for that object. Hope this helps someone!
ryan at ryanparman dot com
27-Mar-2010 10:36
27-Mar-2010 10:36
I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.
You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.
<?php
// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode(new SimpleXMLElement($xml->asXML(), LIBXML_NOCDATA));
?>
5hunter5 at mail dot ru
17-Feb-2010 12:03
17-Feb-2010 12:03
If I want to encode object whith all it's private and protected properties, then I implements that methods in my object:
<?php
public function encodeJSON()
{
foreach ($this as $key => $value)
{
$json->$key = $value;
}
return json_encode($json);
}
public function decodeJSON($json_str)
{
$json = json_decode($json_str, 1);
foreach ($json as $key => $value)
{
$this->$key = $value;
}
}
?>
Or you may extend your class from base class, wich is implements that methods.
Found that much more simple than regular expressions with PHP serialized objects...
olivier dot pons dot no dot spam at gmail dot com
22-Jan-2010 04:13
22-Jan-2010 04:13
Be careful about one thing:
With a string key Php will consider it's an object:
<?php
echo json_encode(array('id'=>'testtext'));
echo json_encode(array('testtext'));
?>
Will give:
{"id":"testtext"}
["testtext"]
Beware of the string keys!
garydavis at gmail dot com
14-Jan-2010 04:38
14-Jan-2010 04:38
If you are planning on using this function to serve a json file, it's important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add ";" to the end.
It took me a while to figure this out so I thought I'd save others the aggravation.
<?php
header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: http://www.example.com/');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
$file='rss.xml';
$arr = simplexml_load_file($file);//this creates an object from the xml file
$json= '('.json_encode($arr).');'; //must wrap in parens and end with semicolon
print_r($_GET['callback'].$json); //callback is prepended for json-p
?>
me at daniel dot ie
15-Nov-2009 05:45
15-Nov-2009 05:45
I had trouble putting the results of mysql_fetch_assoc() through json_encode: numbers being returned from the query were being quoted in the JSON output (i.e., they were being treated as strings). In order to fix this, it is necessary to explicitly cast each element of the array before json_encode() is called.
The following code uses metadata from a MySQL query result to do this casting.
<?php
$mysql = mysql_connect('localhost', 'user', 'password');
mysql_select_db('my_db');
$query = 'select * from my_table';
$res = mysql_query($query);
// iterate over every row
while ($row = mysql_fetch_assoc($res)) {
// for every field in the result..
for ($i=0; $i < mysql_num_fields($res); $i++) {
$info = mysql_fetch_field($res, $i);
$type = $info->type;
// cast for real
if ($type == 'real')
$row[$info->name] = doubleval($row[$info->name]);
// cast for int
if ($type == 'int')
$row[$info->name] = intval($row[$info->name]);
}
$rows[] = $row;
}
// JSON-ify all rows together as one big array
echo json_encode($rows);
mysql_close($mysql);
?>
rlz_ar at yahoo dot com
30-Oct-2009 05:35
30-Oct-2009 05:35
If you have problems with json_encode() on arrays, you can force json_encode() to encode as object, and then use json_decode() casting the result as array:
<?php
$myarray = Array('isa', 'dalawa', 'tatlo');
unset($myarray[1]);
$json_encoded_array = json_encode ( $myarray, JSON_FORCE_OBJECT );
// do whatever you want with your data
// then you can retrive the data doing:
$myarray = (array) json_decode ( $json_encoded_array );
?>
simoncpu was here
20-Oct-2009 11:18
20-Oct-2009 11:18
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.
e.g.:
<?php
$myarray = Array('isa', 'dalawa', 'tatlo');
var_dump($myarray);
/* output
array(3) {
[0]=>
string(3) "isa"
[1]=>
string(6) "dalawa"
[2]=>
string(5) "tatlo"
}
*/
?>
As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.
<?php
$myarray = Array('isa', 'dalawa', 'tatlo');
unset($myarray[1]);
var_dump($myarray);
/* output
array(2) {
[0]=>
string(3) "isa"
[2]=>
string(5) "tatlo"
}
*/
?>
Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such.
SOLUTION: Use array_values() to re-index the array.
http://mike.eire.ca/
10-Aug-2009 10:54
10-Aug-2009 10:54
Note that this function does not always produce legal JSON.
<?php
$json = json_encode('foo');
var_dump($json);
//string(5) ""foo""
$json = json_encode(23);
var_dump($json);
//string(2) "23"
?>
According to the JSON spec, only objects and arrays can be represented; the JSON_FORCE_OBJECT flag available since PHP 5.3 does not change this behaviour. If you're using this to produce JSON that will be exchanged with other systems, adjust your output accordingly.
<?php
$json = preg_replace('/^([^[{].*)$/', '[$1]', $json);
?>
The json_decode function accepts these JSON fragments without complaint.
damon1977 at gmail dot com
28-Jul-2009 09:41
28-Jul-2009 09:41
I wrote a function to make JSON strings more readable. It's very useful for debugging JSON output...
<?php
function jsonReadable($json, $html=FALSE) {
$tabcount = 0;
$result = '';
$inquote = false;
$ignorenext = false;
if ($html) {
$tab = " ";
$newline = "<br/>";
} else {
$tab = "\t";
$newline = "\n";
}
for($i = 0; $i < strlen($json); $i++) {
$char = $json[$i];
if ($ignorenext) {
$result .= $char;
$ignorenext = false;
} else {
switch($char) {
case '{':
$tabcount++;
$result .= $char . $newline . str_repeat($tab, $tabcount);
break;
case '}':
$tabcount--;
$result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
break;
case ',':
$result .= $char . $newline . str_repeat($tab, $tabcount);
break;
case '"':
$inquote = !$inquote;
$result .= $char;
break;
case '\\':
if ($inquote) $ignorenext = true;
$result .= $char;
break;
default:
$result .= $char;
}
}
}
return $result;
}
?>
Istratov Vadim
10-Jun-2009 08:54
10-Jun-2009 08:54
Be careful with floating values in some locales (e.g. russian) with comma (",") as decimal point. Code:
<?php
setlocale(LC_ALL, 'ru_RU.utf8');
$arr = array('element' => 12.34);
echo json_encode( $arr );
?>
Output will be:
--------------
{"element":12,34}
--------------
Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like "LC_NUMERIC, 'en_US.utf8'" before using json_encode.
other at killermonk dot com
20-May-2009 11:55
20-May-2009 11:55
If you are trying to flatten a multi dimensional array, you can also just use serialize and unserialize. It just depends on what you are trying to do.
Sam Barnum
21-Apr-2009 08:01
21-Apr-2009 08:01
Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string. You can batch-encode all the elements of an array with the array_map function:
<?php
$encodedArray = array_map(utf8_encode, $rawArray);
?>
atrauzzi at gmail dot com
08-Apr-2009 09:39
08-Apr-2009 09:39
Here's an idea for people trying to figure out an alternative to implode() to flatten multi-dimensional arrays.
Use json_encode()!
I needed a way to create a hash from an array:
md5(json_encode($multiDimensionalArray)) does the trick!
Happy caching!
andyrusterholz at g-m-a-i-l dot c-o-m
27-Mar-2009 08:17
27-Mar-2009 08:17
For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn't want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.
Note that, because javascript converts JSON data into either nested named objects OR vector arrays, it's quite difficult to represent mixed PHP arrays (arrays with both numerical and associative indexes) well in JSON. This function does something funky if you pass it a mixed array -- see the comments for details.
I don't make a claim that this function is by any means complete (for example, it doesn't handle objects) so if you have any improvements, go for it.
<?php
/**
* Converts an associative array of arbitrary depth and dimension into JSON representation.
*
* NOTE: If you pass in a mixed associative and vector array, it will prefix each numerical
* key with "key_". For example array("foo", "bar" => "baz") will be translated into
* {'key_0': 'foo', 'bar': 'baz'} but array("foo", "bar") would be translated into [ 'foo', 'bar' ].
*
* @param $array The array to convert.
* @return mixed The resulting JSON string, or false if the argument was not an array.
* @author Andy Rusterholz
*/
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "'".addslashes($key)."'";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
?>
aangel at spam dot com
08-Feb-2009 02:50
08-Feb-2009 02:50
Here is a bit more on creating an iterator to get at those pesky private/protected variables:
<?php
class Kit implements IteratorAggregate {
public function __construct($var) {
if (is_object($var)) {
// if passed an object, we are cloning
$this->kitID = $var->kitID;
$this->kitName = $var->kitName;
foreach ($var->productArray as $key => $value) {
$this->productArray[$key] = (array)$value;
}
}
}
...
// Create an iterator because private/protected vars can't
// be seen by json_encode().
public function getIterator() {
$iArray['kitID'] = $this->kitID;
$iArray['kitName'] = $this->kitName;
$iArray['productArray'] = (array)$this->productArray;
return new ArrayIterator($iArray);
}
}
?>
Calling something like $t = json_encode($this->getIterator()); will give you almost what you want:
<?php
{"kitID":"Kit_Essentials-Books.txt",
"kitName":"Essential Books",
"productArray":{"0470043601":{"Category":"Food","ASIN":"0470043601"} } }
?>
Notice that the productArray is converted to an object ignoring the cast I put in front, which is not what I wanted. I haven't figured out how to make sure that encodes as an array.
Regardless, bringing that JSON back into an object using json_decode() will give you just a std object, and the only way I've found to get it into the proper object type is to use a constructor that instantiates the object the way it's supposed to be (see __construct($var) above). Like this:
<?php
$newKit = new Kit(json_decode($t));
?>
Garrett
22-Oct-2008 08:17
22-Oct-2008 08:17
A note about json_encode automatically quoting numbers:
It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:
We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.
This can lead to problems within javascript functions expecting the values to be numeric.
This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.
The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.
stboisvert at nowantspam dot gmail dot com
14-Oct-2008 09:27
14-Oct-2008 09:27
When Using Libraries such as Prototype you may find that once in a while when you return what you believe to be a empty array it will have a different behavior (vis a vis enumerables) than when you give it an associative array. To "fix" this, on your JS you may want to look for extended object properties to verify if it is an empty array or an ocject.
example:
<?php
if (transport.responseJSON['User'].length == undefined){
var user = $H(transport.responseJSON['User']);
}else{
var user = transport.responseJSON['User'];
}
?>
Thanks goes out to :
jani@php.net
This is totally expected behaviour. Please read this:
http://www.json.org/
Note: array and assoc-array are different things. Latter being "object"
in json.
http://bugs.php.net/bug.php?id=45162
[RQuadling] See http://bugs.php.net/bug.php?id=47493. Fixed by using json_encode(array(), JSON_FORCE_OBJECT);
spam.goes.in.here AT gmail.com
09-Aug-2008 08:05
09-Aug-2008 08:05
For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be included in the output into an array in the getIterator() method and return it.
umbrae at gmail dot com
10-Jan-2008 07:21
10-Jan-2008 07:21
Here's a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:
<?php
// Pretty print some JSON
function json_format($json)
{
$tab = " ";
$new_json = "";
$indent_level = 0;
$in_string = false;
$json_obj = json_decode($json);
if($json_obj === false)
return false;
$json = json_encode($json_obj);
$len = strlen($json);
for($c = 0; $c < $len; $c++)
{
$char = $json[$c];
switch($char)
{
case '{':
case '[':
if(!$in_string)
{
$new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
$indent_level++;
}
else
{
$new_json .= $char;
}
break;
case '}':
case ']':
if(!$in_string)
{
$indent_level--;
$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
}
else
{
$new_json .= $char;
}
break;
case ',':
if(!$in_string)
{
$new_json .= ",\n" . str_repeat($tab, $indent_level);
}
else
{
$new_json .= $char;
}
break;
case ':':
if(!$in_string)
{
$new_json .= ": ";
}
else
{
$new_json .= $char;
}
break;
case '"':
if($c > 0 && $json[$c-1] != '\\')
{
$in_string = !$in_string;
}
default:
$new_json .= $char;
break;
}
}
return $new_json;
}
?>
jjoss
24-Oct-2007 09:07
24-Oct-2007 09:07
Another way to work with Russian characters. This procedure just handles Cyrillic characters without UTF conversion. Thanks to JsHttpRequest developers.
<?php
function php2js($a=false)
{
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a))
{
if (is_float($a))
{
// Always use "." for floats.
$a = str_replace(",", ".", strval($a));
}
// All scalars are converted to strings to avoid indeterminism.
// PHP's "1" and 1 are equal for all PHP operators, but
// JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
// we should get the same result in the JS frontend (string).
// Character replacements for JSON.
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a))
{
if (key($a) !== $i)
{
$isList = false;
break;
}
}
$result = array();
if ($isList)
{
foreach ($a as $v) $result[] = php2js($v);
return '[ ' . join(', ', $result) . ' ]';
}
else
{
foreach ($a as $k => $v) $result[] = php2js($k).': '.php2js($v);
return '{ ' . join(', ', $result) . ' }';
}
}
?>
jfdsmit at gmail dot com
23-Oct-2007 04:31
23-Oct-2007 04:31
json_encode also won't handle objects that do not directly expose their internals but through the Iterator interface. These two function will take care of that:
<?php
/**
* Convert an object into an associative array
*
* This function converts an object into an associative array by iterating
* over its public properties. Because this function uses the foreach
* construct, Iterators are respected. It also works on arrays of objects.
*
* @return array
*/
function object_to_array($var) {
$result = array();
$references = array();
// loop over elements/properties
foreach ($var as $key => $value) {
// recursively convert objects
if (is_object($value) || is_array($value)) {
// but prevent cycles
if (!in_array($value, $references)) {
$result[$key] = object_to_array($value);
$references[] = $value;
}
} else {
// simple values are untouched
$result[$key] = $value;
}
}
return $result;
}
/**
* Convert a value to JSON
*
* This function returns a JSON representation of $param. It uses json_encode
* to accomplish this, but converts objects and arrays containing objects to
* associative arrays first. This way, objects that do not expose (all) their
* properties directly but only through an Iterator interface are also encoded
* correctly.
*/
function json_encode2($param) {
if (is_object($param) || is_array($param)) {
$param = object_to_array($param);
}
return json_encode($param);
}
dennispopel(at)gmail.com
26-Aug-2007 07:43
26-Aug-2007 07:43
Obviously, this function has trouble encoding arrays with empty string keys (''). I have just noticed that (because I was using a function in PHP under PHP4). When I switched to PHP5's json_encode, I noticed that browsers could not correctly parse the encoded data. More investigation maybe needed for a bug report, but this quick note may save somebody several hours.
Also, it manifests on Linux in 5.2.1 (tested on two boxes), on my XP with PHP5.2.3 json_encode() works just great! However, both 5.2.1 and 5.2.3 phpinfo()s show that the json version is 1.2.1 so might be Linux issue
php at mikeboers dot com
05-Jul-2007 04:49
05-Jul-2007 04:49
Here is a way to convert an object to an array which will include all protected and private members before you send it to json_encode()
<?php
function objectArray( $object ) {
if ( is_array( $object ))
return $object ;
if ( !is_object( $object ))
return false ;
$serial = serialize( $object ) ;
$serial = preg_replace( '/O:\d+:".+?"/' ,'a' , $serial ) ;
if( preg_match_all( '/s:\d+:"\\0.+?\\0(.+?)"/' , $serial, $ms, PREG_SET_ORDER )) {
foreach( $ms as $m ) {
$serial = str_replace( $m[0], 's:'. strlen( $m[1] ) . ':"'.$m[1] . '"', $serial ) ;
}
}
return @unserialize( $serial ) ;
}
// TESTING
class A {
public $a = 'public for a' ;
protected $b = true ;
private $c = 123 ;
}
class B {
public $d = 'public for b' ;
protected $e = false ;
private $f = 456 ;
}
$a = new A() ;
$a -> d = new B() ;
echo '<pre>' ;
print_r( $a ) ;
print_r( objectArray( $a )) ;
?>
Cheers!
mike
Yi-Ren Chen at NCTU CSIE
02-May-2007 06:55
02-May-2007 06:55
I write a function "php_json_encode"
for early version of php which support "multibyte" but doesn't support "json_encode".
<?php
function json_encode_string($in_str)
{
mb_internal_encoding("UTF-8");
$convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
$str = "";
for($i=mb_strlen($in_str)-1; $i>=0; $i--)
{
$mb_char = mb_substr($in_str, $i, 1);
if(mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match))
{
$str = sprintf("\\u%04x", $match[1]) . $str;
}
else
{
$str = $mb_char . $str;
}
}
return $str;
}
function php_json_encode($arr)
{
$json_str = "";
if(is_array($arr))
{
$pure_array = true;
$array_length = count($arr);
for($i=0;$i<$array_length;$i++)
{
if(! isset($arr[$i]))
{
$pure_array = false;
break;
}
}
if($pure_array)
{
$json_str ="[";
$temp = array();
for($i=0;$i<$array_length;$i++)
{
$temp[] = sprintf("%s", php_json_encode($arr[$i]));
}
$json_str .= implode(",",$temp);
$json_str .="]";
}
else
{
$json_str ="{";
$temp = array();
foreach($arr as $key => $value)
{
$temp[] = sprintf("\"%s\":%s", $key, php_json_encode($value));
}
$json_str .= implode(",",$temp);
$json_str .="}";
}
}
else
{
if(is_string($arr))
{
$json_str = "\"". json_encode_string($arr) . "\"";
}
else if(is_numeric($arr))
{
$json_str = $arr;
}
else
{
$json_str = "\"". json_encode_string($arr) . "\"";
}
}
return $json_str;
}
giunta dot gaetano at sea-aeroportimilano dot it
04-Sep-2006 05:11
04-Sep-2006 05:11
Take care that json_encode() expects strings to be encoded to be in UTF8 format, while by default PHP strings are ISO-8859-1 encoded.
This means that
json_encode(array('àü'));
will produce a json representation of an empty string, while
json_encode(array(utf8_encode('àü')));
will work.
The same applies to decoding, too, of course...
