InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Encapsulating Complex Data Types in a String in PHP
PHP

Encapsulating Complex Data Types in a String in PHP

InfinityCoder November 21, 2016

You want a string representation of an array or object for storage in a file or database. This string should be easily reconstitutable into the original array or object.

Use serialize() to encode variables and their values into a textual form:

1
2
3
4
$pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');
$fp = fopen('/tmp/pantry','w') or die ("Can't open pantry");
fputs($fp,serialize($pantry));
fclose($fp);

To re-create the variables, use unserialize():

1
2
3
// $new_pantry will be the array:
// array('sugar' => '2 lbs.','butter' => '3 sticks'
$new_pantry = unserialize(file_get_contents('/tmp/pantry'));

For easier interoperability with other languages (at a slight performance cost), use json_encode() to serialize data:

1
2
3
4
$pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');
$fp = fopen('/tmp/pantry.json','w') or die ("Can't open pantry");
fputs($fp,json_encode($pantry));
fclose($fp);

And use json_decode() to re-create the variables:

1
2
3
// $new_pantry will be the array:
// array('sugar' => '2 lbs.','butter' => '3 sticks')
$new_pantry = json_decode(file_get_contents('/tmp/pantry.json'), TRUE);

The PHP serialized string that is reconstituted into $pantry looks like:

1
a:2:{s:5:"sugar";s:6:"2 lbs.";s:6:"butter";s:8:"3 sticks";}

The JSON-encoded version looks like:

1
{"sugar":"2 lbs.","butter":"3 sticks"}

The extra business in the serialized string that’s not in the JSON string encodes the types and lengths of the values. This makes it uglier to look at but a little faster to decode.

If you’re just shuttling data among PHP applications, native serialization is great. If you need to work with other languages, use JSON instead.
Both native serialization and JSON store enough information to bring back all the values in the array, but the variable name itself isn’t stored in either serialized representation.
JSON can’t distinguish between objects and associative arrays in its serialization format, so you have to choose which you want when you call json_decode().

A second argument of true, as in the previous example, produces associative arrays.

Without that argument, the same JSON would be decoded into an object of class stdClass with two properties: sugar and butter.
When passing serialized data from page to page in a URL, call urlencode() on the data to make sure URL metacharacters are escaped in it:

1
2
3
4
5
$shopping_cart = array('Poppy Seed Bagel' => 2,
                       'Plain Bagel' => 1,
                       'Lox' => 4);
print '<a href="next.php?cart='.urlencode(serialize($shopping_cart)).
        '">Next</a>';

Serialized data going into a database always needs to be escaped as well.
When you unserialize an object, PHP automatically invokes its __wakeUp() method.
This allows the object to reestablish any state that’s not preserved across serialization, such as database connection.

This can alter your environment, so be sure you know what you’re unserializing.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Printing Correct Plurals in PHP
You want to correctly pluralize words based on the value …

Printing Correct Plurals in PHP

Changing Array Size in PHP
You want to modify the size of an array, either …

Changing Array Size in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

    Categories

    • Bash
    • PHP
    • Python
    • Uncategorized

    InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

    About Us

    Start learning your desired programming language with InfinityQuest.com.

    On our website you can access any tutorial that you want with video and code examples.

    We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

    Popular Tags

    binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

    Archives

    • June 2017
    • April 2017
    • February 2017
    • January 2017
    • December 2016
    • November 2016
    Copyright © 2019 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
    Programming Tutorials | Sitemap