Skip to content
This repository was archived by the owner on Apr 25, 2026. It is now read-only.

Commit b8f71ca

Browse files
committed
Docs: Serialization.
1 parent 503407c commit b8f71ca

1 file changed

Lines changed: 69 additions & 1 deletion

File tree

docs/Usage/Serializing.md

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,72 @@
44

55
# Serializing
66

7-
**TODO**
7+
It's as simple as this:
8+
9+
```c#
10+
using PhpSerializerNET;
11+
12+
string serializedData = PhpSerialization.Serialize(myData);
13+
```
14+
15+
## Simple types
16+
17+
Simple types here means strings, integers, doubles, and `null`. They are very straight forward in how they map.
18+
19+
```c#
20+
Console.WriteLine(PhpSerialization.Serialize("Hello World"));
21+
// Output: s:11:"Hello World";
22+
23+
Console.WriteLine(PhpSerialization.Serialize(12345));
24+
// Output: i:12345;
25+
26+
Console.WriteLine(PhpSerialization.Serialize(true));
27+
// Output: b:1;
28+
29+
Console.WriteLine(PhpSerialization.Serialize(null));
30+
// Output: N;
31+
32+
Console.WriteLine(PhpSerialization.Serialize(3.1415));
33+
// Output: d:3.1415;
34+
```
35+
36+
## Complex types
37+
38+
These are your data structures. Anything `ICollection`, arrays, structs and objects.
39+
40+
### Collections and arrays
41+
42+
These will always use the array notation of `a:<length>:{<data>}`.
43+
44+
`IList` and arrays will be serialized using integer keys, starting with an index of 0.
45+
46+
```c#
47+
Console.WriteLine(PhpSerialization.Serialize(new List<int>(){ 10, 20, 30 });
48+
// Output: a:3:{i:0;i:10;i:1;i:20;i:2;i:30;}
49+
50+
Console.WriteLine(PhpSerialization.Serialize(new int[]{ 10, 20, 30 });
51+
// Output: a:3:{i:0;i:10;i:1;i:20;i:2;i:30;}
52+
```
53+
54+
`IDictionary` implementations will use whatever key is used in the dictionary instead of the integer. PHP arrays are always associative arrays with arbitrary keys, so this is perfectly valid.
55+
56+
```c#
57+
Console.WriteLine(PhpSerialization.Serialize(
58+
new Dictionary<object, object>{
59+
{ "a", 10 },
60+
{ 1, 20 },
61+
{ true, 30 },
62+
}
63+
);
64+
// Output: a:3:{s:1:"a";i:10;i:1;i:20;b:1;i:30;}
65+
```
66+
67+
## Objects and structs
68+
69+
By default, objects and structs will be serialized into an array with string keys.
70+
71+
You can instead use object notation by annotating your type declaration with [[PhpClass]](../Attributes/PhpClass.md) or by implementing [IPhpObject](../Types/IPhpObject.md).
72+
73+
## Enums
74+
75+
By default, enums are serialized into strings, using their `.ToString()` representation. You can also specify integer serialization with the [NumericEnums](../Options/PhpSerializiationOptions.md#NumericEnums) option.

0 commit comments

Comments
 (0)