up one level
---
Challenge - How to Serialize a String to JSON in PHP
In the context of web development, I was recently challenged to:
Serialize "PHP".
Below is a description of one way to complete the challenge.
I completed the challenge, at the same time as learning a bit about web development and learning a bit about array serialization to JSON in PHP.
An internet search, on how to serialize a string in PHP, yielded this article: ( http://stackoverflow.com/questions/...-unserialize ). Reading it taught me some about the why and how of serialization in PHP.
Reviewing the challenge question. It was a bit open-ended, and requested to serialize the string.
To make it more clear that I had serialized the string, I decided it would be better to first split it into characters, then encode it in JSON, then echo the string back out to the screen as json-formatted text.
How?
Well, if I just serialized the string, like:
<?php
serialize('PHP');
// output:
//
?>
, then there would be no output; the string would just be serialized in memory on the server.
So I thought I would echo it out on the screen via the browser window:
<?php
echo serialize('PHP');
// output:
// s:3:"PHP";
?>
I think this is a bit better.
But is this too simple? I feel the question has an unwritten implication that, as often is the case in a web programming context, the purpose of serialization is to serialize it into a common format to be able to send it somewhere else where it would be consumed, for example parsed by a JavaScript client application. So it would be better to serialize it in a common format like XML or JSON. I choose JSON. So I encode it in JSON instead, like this:
<?php
echo json_encode('PHP');
// output:
// "PHP"
?>
Hm, but now It seems unclear that it was serialized, and also it doesn't look like JSON format either -- there's little proof that I did any work. I feel I need to show my work a bit more, via the results. What if I split the string first, into an array, by using the PHP str_split() function?
<?php
echo json_encode(str_split('PHP'));
// output:
// ["P","H","P"]
?>
That's better, but it still doesn't look like JSON data. I look in the PHP manual for ideas: ( http://php.net/manual/en/function.json-encode.php ). I find the JSON_FORCE_OBJECT option, and use it:
<?php
echo json_encode(str_split('PHP'), JSON_FORCE_OBJECT);
// output:
// {"0":"P","1":"H","2":"P"}
?>
That's better -- challenge done -- Ship it! (à la http://scotchisforshippers.com/ )
This has been a description of one way to complete the coding challenge, at the same time as learning a bit about web development and learning a bit about array serialization to JSON in PHP.
Tags: #mingling
Note: This post was pre-published on November 18, 2016.
[2019 edit: Moved to: https://i̶n̶v̶e̶s̶t̶o̶r̶w̶o̶r̶k̶e̶r̶.̶c̶o̶m̶/2016/... .html.]