【问题标题】:Receive JSON object in index php, process JSON info on page and send back JSON response. How to go about it?接收索引 php 中的 JSON 对象,处理页面上的 JSON 信息并发送回 JSON 响应。怎么办?
【发布时间】:2012-05-02 10:26:52
【问题描述】:

我的情况是,网站会将用户重定向回我们的网站(在 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 新手。

【问题讨论】:

    标签: php json request response


    【解决方案1】:

    刚刚测试了你的脚本,它运行良好......它们是两个可能的原因

    A.无效URL

    B.卷曲请求失败

    把你的脚本放在上面

    error_reporting(E_ALL);
    ini_set('display_errors','On');
    

    并且还使用它来捕获 curl 错误

    if(curl_exec($ch) === false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    

    【讨论】:

    • 经过进一步咨询,我发现我正在寻找的东西是不可能的。感谢您抽出时间来回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多