-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?

Paul Yorde
  • 75
  • 1
  • 2
  • 12
  • 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. – Ja͢ck Sep 09 '13 at 02:18

1 Answers1

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?

Community
  • 1
  • 1
LoganEtherton
  • 495
  • 4
  • 12