0

I am getting api response in plain text format. So operation with response data I need to encode the response into JSON format. Then I can easily grab the desire response data and use it.

Request CODE(Sample) ::

        $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;

        }

Response CODE(Sample) ::

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

I want to encode The response is in JSON format like this -

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

and also grab the data like this -

 $id=array["id"];
 echo $id;
Ashiqur Rahman
  • 425
  • 7
  • 21

3 Answers3

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);

Output:

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

To get data back from 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;

Output:

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 
Nuhil Mehdy
  • 2,424
  • 1
  • 21
  • 23
0

Do it by json_encode. Use it like this

var_dump(json_decode($response, true));

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

Ranjit
  • 1,684
  • 9
  • 29
  • 61
-2

This method works for Java, you can convert it to your language if each line ends with \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 += "\"}";

}

Milon
  • 2,221
  • 23
  • 27
  • $lines = explode("\n", $response); $output = Array(); $thisElement = & $output; foreach($lines as $line) { $elements = explode(":", $line); if (count($elements) > 1) { $thisElement[trim($elements[0])] = $elements[1]; } if(strstr($line, "{")) { $elements = explode("{", $line); $key = trim($elements[0]); $output[$key] = Array(); $thisElement = & $output[$key]; } if(strstr($line, "}")) { $thisElement = & $output; } } echo '
    ';
       print_r($output);
       echo '
    ';
    – Ashiqur Rahman Mar 16 '17 at 07:57
  • I am using this to convert the txt into plain text .. but I get "t" or "tt" in the output – Ashiqur Rahman Mar 16 '17 at 07:58