私は、ウェブサイトがユーザーを私たちのサイト (index.php) にリダイレクトし、JSON リクエストを送信する状況にいます。JSON 要求を解析し、それに応じて処理してから、JSON 応答を返信します。
このコードを使用して、index.php で JSON 入力要求を受け取ります。
$data_back = json_decode(file_get_contents('php://input'));
//process $data_back
// create json response
$response = array("RESPONSE_CODE"=>"0","RESPONSE_DESCRIPTION"=>"OK","PAYMENT_ID"=>"XYZ");
// set header as json
header("Content-type: application/json");
// send response
echo json_encode($response);
ただし、echo を使用すると、コンテンツはメイン ページ (index.php) に表示されます。エコーを使用しないと、リクエストを送信した他のサイトにレスポンスが返されず、入力ストリームでデータを受信することもできません。
次のコードで他のサイトをシミュレートしようとしています:
//set POST variables address and json string
$url = 'http://XYZ.com/MYSITE/index.php';
$fields = array("CARD_NUMBER"=>"123","CUSTOMER_NAME"=>"ABC","RECEIVED_AMOUNT"=>"5000","REQUEST_TYPE"=>"PAYMENT_RECEIVED");
//url-ify the data for the JSON POST
$fields_string = json_encode($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);
//execute post
$jsonResult = curl_exec($ch);
//close connection
curl_close($ch);
$results = json_decode($jsonResult, true);
これにアプローチする方法がわかりません。index.php で JSON を処理し、応答も返すことができるか教えてください。私はJSONが初めてです。