简体   繁体   English

如何用POST发送数据并用php中的json接收

[英]how to send data with POST and receive with json in php

i want to connect to API.but i need to send data with post, but receive in json. 我想连接到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);
?>

when i run my code, receive that Error: 当我运行我的代码时,收到该错误:

file_get_contents(url_here): failed to open stream file_get_contents(url_here):无法打开流

To receive in in json format, you should do echo json_encode($myArray) as 要以json格式接收,您应该将echo json_encode($myArray)做为echo json_encode($myArray)

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

if you want to send a post request to a server, you should use cURL or something similar. 如果要向服务器发送发布请求,则应使用cURL或类似的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM