如何将纯文本响应编码为JSON并使用PHP CURL获取特定数据

时间:2017-03-16 07:32:27

标签: php json api curl encode

我以纯文本格式获得api响应。因此,使用响应数据进行操作我需要将响应编码为JSON格式。然后我可以轻松获取所需的响应数据并使用它。

请求代码(样本)::             

        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "http://api.arshohag.me/test",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS =>      "login=testapp&key=152456&md5=chasdg4as432&action=test",
          CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache",
            "content-type: application/x-www-form-urlencoded",
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          echo "cURL Error #:" . $err;
        } else {
          echo $response;

        }

响应代码(样本)::

id=2566546
authentication_key=74448975
error_code=0
error_txt=Test Ok

我想编码响应是JSON格式,如下所示 -

{
  "id" : "2566546",
  "authentication_key" : "74448975",
  "error_code" : "0",
  "error_txt" : "Test Ok"
}

并抓住这样的数据 -

 $id=array["id"];
 echo $id;

3 个答案:

答案 0 :(得分:3)

$rawText = "
id=2566546
authentication_key=74448975
error_code=0
error_txt=Test Ok
";

// Split by new line
// array_filter to skip empty values
$linesArray = array_filter(preg_split('/\R/', $rawText));

$craftedArray = array();
foreach($linesArray as $line) {
  $tempArray = explode("=", $line);
  $craftedArray[$tempArray[0]] = $tempArray[1];
}

// Encode to JSON Object
echo json_encode($craftedArray);

输出:

{
id: "2566546",
authentication_key: "74448975",
error_code: "0",
error_txt: "Test Ok"
}

从JSON获取数据:

// Decode JSON. Assume JSON object is stored in $jsonData
$decodedData = json_decode($jsonData);
var_dump($decodedData);

// Access like below
$id = $decodedData->id;
echo "\nID is: ".$id;

输出:

object(stdClass)#1 (4) {
  ["id"]=>
  string(7) "2566546"
  ["authentication_key"]=>
  string(8) "74448975"
  ["error_code"]=>
  string(1) "0"
  ["error_txt"]=>
  string(7) "Test Ok"
}

ID is: 2566546 

答案 1 :(得分:0)

通过json_encode完成。像这样使用它

var_dump(json_decode($ response,true));

参考http://php.net/manual/en/function.json-encode.php

答案 2 :(得分:-2)

此方法适用于Java,如果每行以\ r \ n

结尾,则可以将其转换为您的语言
String jsonStringConverter(String stringResponse) {
String[] parts = stringResponse.split("\\r\\n");
String jsonString = "{\"";
for (int i = 0; i < parts.length; i++) {
    jsonString += parts[i].replace("=", "\":\"");
    jsonString += (i < parts.length - 1) ? "\", \"" : "";
}
return jsonString += "\"}";

}