我想在php中发送带有帖子的Json对象。如何发送json对象发布它。我在这里尝试了几个帖子,但它没有用。
这是我试过的代码:
function get_user_post_other_count($user_id, $call_for)
{
$params = array('user_id' => $user_id,
'call_for' => $call_for);
// Build Http query using params
$query = json_encode($params);
// Create Http context details
$contextData = array(
'method' => 'POST',
'header' => 'Content-Type: application/json' . "\r\n" . 'Content-Length: ' . strlen($query) . "\r\n",
'content' => $query);
$context = stream_context_create(array('http' => $contextData));
$result = file_get_contents(USER_PROFILE_COUNTER, false, $context);
$json_decoded = json_decode($result, true);
return $json_decoded;
}
答案 0 :(得分:2)
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => json_encode($data)
)
);
$fp = fopen('http://url', 'r', false, $context_options);
答案 1 :(得分:1)
使用json和ajax将javascript obj发送到php:
JS:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
在php中使用该对象:
$obj = json_decode($_POST["myData"]);
echo $obj->var;
答案 2 :(得分:0)
第1步:在您的php文件中添加此功能:
<?php function do_post($url, $data, $optional_headers = null) { $params = ['http' => ['method' => 'POST', 'content' => $data]]; if ($optional_headers !== null) { $params['http']['header'] = $optional_headers; } $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) { throw new Exception("Exception caused with $url, $php_errormsg"); } $response = @stream_get_contents($fp); if ($response === false) { throw new Exception("Error reading response from $url, $php_errormsg"); } return $response; }
第2步:相应更改功能
function get_user_post_other_count($user_id, $call_for) {
$params = array('user_id' => $user_id, 'call_for' => $call_for);
$query = json_encode($params);
$response = do_post($url, $query);
return json_decode($response, true);
}
我会在这里推荐curl
。
答案 3 :(得分:-1)
使用PHP Curl http://php.net/manual/en/curl.examples.php
$ ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);