PHP 的JSON傳送通訊流程

Server side:

<?php

$json = file_get_contents(‘php://input’);
$obj = json_decode($json);

if($obj->name!=””)
$result[“ok”]=1;
else
$result[“ok”]=0;

echo json_encode($result);

?>

Client side:

<?php
$data[“name”]=”Blah blah”;
$data_string = json_encode($data);

$ch = curl_init(‘https://jacch.php5.idv.tw/json.php’);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Content-Type: application/json’,
‘Content-Length: ‘ . strlen($data_string))
);

$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);

?>