Post json object with php(http post)?
I need to post json object with http post request and to handle responses.
json objec开发者_如何转开发t :
{
"my_json" : "12345"
}
I wrote somethinh like this,but this don't work.
$url = "http://localhost/my_json.json";
$json_Data = file_get_contents($url,0,null,null);
print_r($json_Data);
And it doesn't print anything.
Help please.
Client:
<?php
$data = array('foo' => 'bar', 'red' => 'blue');
$ch = curl_init();
$post_values = array( 'json_data' => json_encode( $data ) );
curl_setopt($ch, CURLOPT_URL, 'http://localhost/server.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_values);
$data = curl_exec($ch);
if(!curl_errno($ch))
{
echo 'Received raw data' . $data;
}
curl_close($ch);
?>
Server (server.php):
<?php
$data = json_decode( $_POST['json_data'] );
// ... do something ...
header('Content-type: text/json');
print json_encode($response);
?>
$url = "http://localhost/my_json.json";
$json_Data = file_get_contents($url,0,null,null);
$new = json_decode($json_Data);
print_r($new);
I think that might do it
Try this:
$jsonFile = 'http://localhost/my_json.json';
$jsonData = file_get_contents($jsonFile);
$phpData = json_decode($jsonData);
print_r($phpData);
The problem may be from the file_get_contents extraneous arguments :
- The 2d arg should be a boolean and is optional (default value is false)
- The 3rd arg is ok
- The 4th should be an integer, is optional (default value is -1)
So you should try $json_Data = file_get_contents($url);
Furthermore to view the data in your browser you should try with header('Content-type: text/plain');
just before outputting with print_r() so that no processing will be made by your browser
To be sure there is really nothing sent to your browser, you may also try FireFox + FireBug to see HTTP replies...
精彩评论