JSON Response with REST GET - PHP


JSON Response with REST GET - PHP

我使用cURL和REST访问数据库和查询搜索,当我使用echo $response:时,我得到以下响应

HTTP/1.1 200 OK Date: Fri, 05 Aug 2016 06:53:02 GMT Server: Apache Content-Language: en-US RNT-Time: D=58292 t=1470379982660626 RNT-Machine: 128.65 Transfer-Encoding: chunked Content-Type: application/json { "items": [ { "tableName": "Country", "count": 1, "columnNames": [ "id" ], "rows": [ [ "12" ] ] } ], "links": [ { "rel": "self", "href": "https://test.cust.com/services/rest/connect/v1.3/queryResults?query=select%20ID%20from%20CO.Country%20where%20CO.Country.Country=%27USA%27" }, { "rel": "canonical", "href": "https://test.cust.com/services/rest/connect/v1.3/queryResults" }, { "rel": "describedby", "href": "https://test.cust.com/services/rest/connect/v1.3/metadata-catalog/queryResults", "mediaType": "application/schema+json" } ] } 

我试着使用JSON_decode(),但到目前为止我一无所获,我如何在这里获得我的参数?更具体地说,是"id"值。

如果我说对了,你有两个选项:

  • 关闭接收标头curl_setopt($ch, CURLOPT_HEADER, 0)
  • 'r'n'r'n打断你的回答,你会得到headerbody
list($header, $body) = explode("'r'n'r'n", $response, 2)

这里发布的响应看起来像是发送到客户端浏览器的服务器响应

因此,您几乎没有解析此数据的选项

  1. 若必须使用PHP解析此响应,那个么您可以尝试通过以下方式在PHP中使用parse_str()解析数据。

    if (FALSE !== (stripos($response, '{'))) {
    $data = trim(substr($response, stripos($response, '{')));
        $data_arr = array();
        parse_str($data, $data_arr);
        print_R($data_arr);
        //Digging down using parse_str() in php
    } else {
        echo "No data found.";
    }
    
  2. 使用客户端javascript/jquery/客户端脚本从浏览器上的响应中解析json。

  3. 使用Curl将标头作为数组返回

您不需要使用JSON_decode()。

用途:

$obj = $_POST['items']; // for post

获取:

$obj = $_GET['items']; 

在@eevive的帮助下,我能够让它工作:

1-接收头curl_setopt($ch,CURLOPT_HEADER,0)

2-$test=$res->items[0]->rows[0];echo $test[0];

$response;//Suppose your respond is this.
$obj = json_decode($response);

然后您可以访问您的参数。示例:$obj->项目