-1

I want to send user submitted values from a form to a web address. I am using PHP to accomplish this. The book I'm working out of, PHP for the Web by Larry Ullman uses variables to store the form values, like this:

$input = $_POST['value']; 

<form>
<input type="textbox" id="value">
<input type="submit" value="submit">
</form

Next I would send those values to the web address like this

$req = "http://webaddress/?value=$input";

Now I would like to get a json response from the web address. like this:

$response = json_decode(file_get_contents($req));

That is my question. How does that response get from the web address to my variable?

1
  • 1
    Wait, you want to know how json_decode() and file_get_contents() work? Your given code does what you want. It's a bit unclear what the problem is. Commented Sep 9, 2013 at 2:18

1 Answer 1

1

json_decode decodes a valid json string into an array. So, a json string that looks like

'{"a":1,"b":2,"c":3,"d":4,"e":5}' 

would end up in an array with key/value pairs corresponding to your json string, such as:

["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)

You can pass json encoded strings and receive them through $_GET. http_build_query does this for you:

http_build_query

Using http_build_query, you'll get code that looks like this:

http_build_query(array('a' => array(1, 2, 3))) // "a[]=1&a[]=2&a[]=3"

http_build_query(array(

    'a' => array(
        'foo' => 'bar',
        'bar' => array(1, 2, 3),
     )
)); // "a[foo]=bar&a[bar][]=1&a[bar][]=2&a[bar][]=3"

Then you can use json_decode on the $_GET key (in this case, $_GET['a'] that you set on encoding. In case it wasn't clear, where you see multiple brackets, such as a[bar][], that's referring to a multi-dimensional array. You don't necessarily need to create more than a single dimensional array.

Check out this answer:

How to pass an array via $_GET in php?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.