PHP and WDDX - Page 2
September 4, 2002
As previously stated, a WDDX module has been available for PHP since version
4.0 of the language. Created by Andrei Zmievski, this WDDX module includes
standard serialization and deserialization functions to convert PHP variables
and arrays into WDDX-compatible data structures.
If you're using a stock PHP binary, it's quite likely that
you'll need to recompile PHP to add support for this library to your PHP
build (detailed instructions for accomplishing this are available in Appendix A,
"Recompiling PHP to Add XML Support").
Encoding Data with WDDX
PHP's WDDX module offers a number of different ways to encode data into
WDDX. The following sections demonstrate this by using the following:
The wddx_serialize_value() function
The wddx_serialize_vars() function
The wddx_add_vars() function
The wddx_serialize_value() Function
The simplest way to encode data into WDDX (and the one I will use most
frequently in this chapter) is via the wddx_serialize_value() function,
which is used to encode a single variable into WDDX. Listing 5.3 demonstrates
its application.
Listing 5.3 Serializing a Single Variable with wddx_serialize_value()
<?php
$flavor = "strawberry";
print wddx_serialize_value($flavor);
?>
Listing 5.4 demonstrates the result.
Listing 5.4 A WDDX Packet Generated via wddx_serialize_value()
<wddxPacket version='1.0'>
<header/>
<data>
<string>strawberry</string>
</data>
</wddxPacket>
Manual Labor
Note that PHP typically generates
the WDDX packet as one long string. This can sometimes get confusing, so I
manually indented and spaced out some of the output listings in this chapter for
greater readability. Whitespace within a WDDX packet, but outside WDDX elements,
is ignored by the WDDX deserializer; whitespace embedded within a WDDX element
is, obviously, preserved.
As Listings 5.5 and 5.6 demonstrate, this works with arrays, too.
Listing 5.5 Serializing a PHP Array with wddx_serialize_value()
<?php
$flavors = array("strawberry", "chocolate", "raspberry", "peach");
print wddx_serialize_value($flavors);
?>
Listing 5.6 A WDDX Packet Representing an Array
<wddxPacket version='1.0'>
<header/>
<data>
<array length='4'>
<string>strawberry</string>
<string>chocolate</string>
<string>raspberry</string>
<string>peach</string>
</array>
</data>
</wddxPacket>
XML and PHP
XML and PHP
PHP and WDDX - Page 3
|