Serialize/unserialize PHP object-graph to JSON - php

I wanted to serialize a complete PHP object-graph to a JSON string representation, and unserialize it back to an identical PHP object-graph.
Here is a summary of options I considered, and reasons why they don't work for me:
serialize() doesn't do what I want, because it uses a format specific to PHP. I want a format that is widely supported by most languages, and human-readable/editable.
json_encode() doesn't do what I want, because it only does simple values and arrays, not objects. (I'm actually using this in my implementation, see below.)
var_export() doesn't handle circular references, and doesn't do what I want (see above.) (note that my current implementation does not handle circular references either - see comments and reply below for clarification of this issue.)
Sebastian Bergmann's Object Freezer is a nice implementation, but it doesn't do what I want either - it uses a very long form, and relies on stuffing serialized objects with GUIDs.
Serialized doesn't do what I want - it does not actually perform serialization, it parses the output of serialize() and produces a different representation, e.g. XML, but is unable to parse that representation. (it also does not support JSON - XML is very long form, and is not what I want.)
I now have a working implementation to share:
https://github.com/mindplay-dk/jsonfreeze
The JSON-representation of the object-graph looks like this:
{
"#type": "Order",
"orderNo": 123,
"lines": [{
"#type": "OrderLine",
"item": "milk \"fuzz\"",
"amount": 3,
"options": null
}, {
"#type": "OrderLine",
"item": "cookies",
"amount": 7,
"options": {
"#type": "#hash",
"flavor": "chocolate",
"weight": "1\/2 lb"
}
}],
"paid": true
}
This approach is designed to work for a pure tree-structure aggregate - circular references are not allowed, nor multiple references to the same objects. In other words, this is not general-purpose like e.g. serialize() and unserialize() which function for any PHP object-graph.
In my initial approach I used a serialized form that was essentially a base-0 list of objects. The first object in the list (number 0) is the root of the serialized object-graph, any other objects are stored in the order they're found.
In the current implementation, the JSON representation resembles the original tree-structure to the extend that this is possible, making it possible to actually work with the JSON representation of an object-graph in JavaScript. The only deviation is the magic #type property (prefixed with # to prevent collision with property-names) and the #hash "type", used to distinguish array-type hashes (stored as JSON objects) from regular array-type arrays (stored as JSON arrays).
I'm leaving these notes about the previous version here for historical purposes.
Circular references are handled simply by never storing nested objects inside the serialized representation of each object - instead, any object-reference is stored as a JSON-object with the object-index - e.g. {"__oref":2} is a reference to the object with index 2 in the object-list.
I'm having a problem with array-references in my implementation - when I var_dump() inside the code that restores references to objects to the array, they are being populated, but at some point the array gets copied, and you end up with the empty copy. I've tried placing & characters everywhere in the code, but regardless of where I pass by reference, the end-result is an empty array.

The finished script (posted above) meets my precise requirements:
Serialize and unserialize an entire aggregate.
Have a JSON representation that closely resembles the original data-structure.
Do not pollute the data-structure with dynamically generated keys or other data.
It does not handle circular references. As pointed out in a comment above there is no right way to store circular references or multiple references to the same object, as these are all equal. Realizing this, I decided my object-graph must be a regular tree, and accepted this limitation as "a good thing".
update: the ouput can now be formatted with indentation, newlines and whitespace - it was important for me to have a human-readable (and source-control friendly) representation for my purposes. (The formatting can be enabled or disabled as needed.)

I don't know if this is what you are after, but if you are only interested in getting at public properties of a object, get_object_vars($obj) will do the trick.
<?php
class foo {
public $fname = "John";
public $sname = "Doe";
private $status = null;
static $type = "person";
}
$obj = new foo;
print_r( (get_object_vars($obj)) );
print json_encode(get_object_vars($obj));
?>
Will output :
Array ( [fname] => John [sname] => Doe )
{"fname":"John","sname":"Doe"}
The above method is useless for accessing function references and private variables but you might be able to use this in conjunction with some more code to knock up what you want.
Dinesh.

Related

To call a particular column/field from an array using PHP [duplicate]

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How to extract data from (array?) with colons [duplicate]

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How do i format a template string with this kind of data? [duplicate]

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

PHP access nested object properties from a string literal

I'm trying to come up with a simple approach for extracting data from a multitude of json data sources where the reference is stored in a string literal. This is easy to do when the object structure is known but is there any way to get php to interpret the string literal as it would directly in code?
$data = json_decode('
{
"foo": 1,
"object": {
"foo": 1.1,
"bar": 1.2
},
"array": [
"foo",
"bar"
]
}
');
// Explicitly coded reference all work, of course
var_dump($data->foo); // int(1)
var_dump($data->object->foo); // float(1.1)
var_dump($data->array[0]); // string(3) "foo"
And I know that I can access an object's property from a string literal like this:
$string = 'foo';
var_dump($data->$string); // int(1)
var_dump($data->object->$string); // float(1.1)
Is there any way to go about achieving this for the second and third references, without having to break up the string and loop through the object recursively until each element is found?
$string = 'object->foo';
var_dump($data->$string);
$string = 'array[0]';
var_dump($data->$string);
If there is nothing native to PHP for handling this, is there a library or anything that I could use to make this process easier?
Edit: To provide some extra clarity, this is an application where a JSON feed can be configured through the UI and an administrator can extract values from the JSON feed. This works fine for simpler JSON structures but breaks down when they're trying to pull a value such as $foo->bar->baz[0]->qux->corge. I'm trying to find an easier way to get values such as this when the structure changes and I can't account for every possibility within the code.
Since you are using JSON, i‘d use JSON Pointers. Here is their official spec
What they do is providing a query language for json objects (similar to XPath for XML). Accessing your foo within object would result in a query like /object/foo.
Now you‘d have your users specify the json pointer queries, and use a json pointer library to perform the actual queries. This has the advantage that if you ever decide to ditch PHP for say Java, you’d only need to use a JSON Pointer implementation for Java and your users won‘t be impacted by the change.

How to use php serialize() and unserialize()

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

Categories