【问题标题】:how to send data with POST and receive with json in php如何在 php 中使用 POST 发送数据并使用 json 接收
【发布时间】:2017-05-31 02:02:12
【问题描述】:

我想连接到 API。但我需要通过 post 发送数据,但在 json 中接收。

    <?php
$params = array (
'user_name' => '1521',
'user_password' => '8554',
'webservice_user'=>'test',
'token'=>'202cb962ac59075b964b07152d234b70');
$query = http_build_query ($params);
$contextData = array (
'method' => 'POST',
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
$result =  file_get_contents (
'IP_ex/login',
false,
$context);
echo($result);
?>

当我运行我的代码时,收到该错误:

file_get_contents(url_here):打开流失败

【问题讨论】:

标签: php json api http-post


【解决方案1】:

要以json格式接收,你应该echo json_encode($myArray) as

<?PHP
header('Content-Type: application/json');
echo json_encode($myArray);

如果你想向服务器发送一个 post 请求,你应该使用cURL 或类似的东西。

【讨论】:

猜你喜欢
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 2011-05-21
  • 1970-01-01
  • 2018-09-17
相关资源
最近更新 更多