The PHP snippet encodes $input as JSON and makes a HTTP POST operation to a given URL.
The response is also decoded from JSON back to a native PHP data type.
/* POST JSON encoded version of $input to $url */
/* By Tim Hastings, http://www.nonhostile.com/howto-http-post-json-using-php.asp */
function JsonPost($url, $input) {
// encode and prepare headers
$json = json_encode($input);
$contentLength = strlen($json);
$headers = "Content-type: application/json\r\nContent-Length: {$contentLength}\r\n";
// populate the options,
$options = array(
'http' => array(
'method' => 'POST',
'header' => $headers,
'ignore_errors' => true,
'content' => $json
)
);
// create context
$context = stream_context_create($options);
$fp = @fopen($url, 'rb', false, $context);
if (!$fp) {
// failed here
$resp = null;
} else {
// get the response and decode
$resp = stream_get_contents($fp);
$resp = json_decode($resp, true);
// close the response
fclose($fp);
}
// decode JSON response
return $resp;
}
891 comments,
PHP, Saturday, September 11, 2010 18:29


