1

I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST

In RoR, I can get the two values by using params["name"] & params["age"]

But I don't know how to get them in PHP.

I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.

In my PHP code, I has tried something like this:

<?php
    $json_string = $_POST['params'];

    $json_object= json_decode($json_string);
    print_r($json_object);

    echo $json_object->name;
    echo " ";
    echo $json_object->age;
?>

Then I has tested the PHP with terminal and I got the correct result

curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php

It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'

Is it the correct way to parse JSON in PHP?

4
  • 3
    the content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. a json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again. Commented Nov 3, 2012 at 21:21
  • @MarcB Thanks for your comment, so the way I used to pass the JSON into PHP is correct ? Commented Nov 4, 2012 at 8:20
  • yes, as long as what you pass into json_decode is the json string, then it's valid, regardless of the mime-type it was sent across with. Commented Nov 5, 2012 at 0:01
  • @MarcB Thanks you so much :) You can reply to this question then I can 'tick' on your answer :) Commented Nov 7, 2012 at 15:48

1 Answer 1

2

The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.

As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.