2017-01-16 104 views
0

我想連接到API,但我需要使用post發送數據,但是需要在json中接收數據。如何使用POST發送數據並在php中使用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): failed to open stream

+0

可能重複的[使用php發送json post](http://stackoverflow.com/questions/6213509/send-json-post-using-php) – bashoogzaad

回答

1

以JSON格式接收,你應該做echo json_encode($myArray)作爲

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

如果你想發個帖子請求服務器,您應該使用cURL或類似的東西。

+0

我將不勝感激給我一個非常簡單的例子 – user2254798

+0

This one很簡單http://stackoverflow.com/a/29601842/1640606但你必須下載Guzzle庫。或者這個用於捲曲http://stackoverflow.com/a/2138534/1640606 – samayo

相關問題