Chapter 4: Data Formats 125
PART I
The benefit of this format is that everything on the server side is decoded automatically
just like a normal x-www-form-urlencoded submission, though now data is presented in
an array format as well. We provide a simple PHP example that echoes the received data in
this format.
<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
echo "<strong>Payload</strong><div class='data'>";
$varList = "";
$varString = "";
/* $_POST can be used as well but $_REQUEST will include
cookies so be careful */
if (count($_GET) > 0)
{
echo "GET Query String: ";
echo $_SERVER['QUERY_STRING']. "<br /><br />";
printObjects($_GET);
echo "<br />";
}
echo "</div>";
function printObjects($obj, $indexString)
{
foreach($obj as $keyStr=>$val)
{
$key = $keyStr;
if (isset($indexString))
$key = $indexString. "[". $key. "]";
if (is_array($val))
printObjects($val, $key);
else
echo $key. "=". $val. "<br />";
}
}
?>
There is a limitation to this format in that it is not possible to have disassociated arrays
containing multiples objects. For example:
"stooge" : [{"name" : "Moe"}, {"leader" : true }]
would not work as expected. It forms the query string here:
stooge[][name]=Moe&stooge[][leader]=true
which then results in two occurrences of the stooge array rather than the nesting:
stooge[0][name]=Moe
stooge[1][leader]=true
This format is interesting, but if a more general object serialization is desired, it is better
to put data in JSON format as described later in the chapter.