Parsing a php into json

I am a newbie or get started with JSON as my job have some work, now i am blank about JSOn and i was wondering, how can i submit a form using php into JSON or to a webservice that take JSON. I hope you will excuse me for not being descriptive, as i have no clue of JSON

When you have a JavaScript object such as:

var data = {
    firstName: "Paul",
    lastName: "Wilkins",
    city: "Christchurch",

JSON is nothing more than the object (the curly braces and their contents) that was assigned to data.

So in this case, if you were to use JSON.stringify(data) the JSON text that you would get is:


The whole point of the JSON convention is that it results in easy to send text-based data, that is easily turned back in to meaningful content.

For example, if PHP receives the JSON content, you can easily decode it using:

$json = filter_input(INPUT_GET, "json", FILTER_SANITIZE_STRING);
$data = json_decode($json, true); // true for array, false or removed for object

In case you haven’t come across filter_input before, it’s an improved version of $_GET[“json”]

If you dumped the contents of $data:


The output would be:

array(3) {
    ["firstName"] => string(4) "Paul"
    ["lastName"] => int(7) "Wilkins"
    ["city"] => int(12) Christchurch

So that’s a bit of background on JSON. I’ll let others help with the webservice side of things.

1 Like

To get result of json_decode() as array, second argument should be specified

$data = json_decode($json); //returns object
$data = json_decode($json, true); //returns array

Thanks, have updated the post to show that too.

Thanks for detailed answer @Paul_Wilkins . But question is how you pass it from php form. I don’t know the first step, so second step is kind of hard to picture.

When the form is submitted the content of the form is passed to the script identified by the action attribute on the form tag. All of the content are passed in the $_POST array with their names coming from the name attributes on the individual form fields. If you want to convert the form to JSON you would need to do that after the script has read the values into $_POST.

So, now here is a simple form. How about i send and get a response back from json file for verifying username and password, then knowing i have logged in with correct credentials.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.