PHP- Access json response data from curl-ThrowExceptions

Exception or error:

I succesfully returned response. But I have trouble parsing it:

"HTTP/1.1 200 OK\r\nDate: Mon, 16 Mar 2020 13:44:57 GMT\r\nContent-Type: application/json\r\nContent-Length: 369\r\nConnection: keep-alive\r\nx-amzn-RequestId: 9820238c-fe40-47dd-a848-3b2d01a929a2\r\nx-amz-apigw-id: JfFh7HBmrPEFrQw=\r\nX-Amzn-Trace-Id: Root=1-5e6f82d9-dff16fe84c4297a6aa2a3ce4;Sampled=0\r\n\r\n{\"ok\":true,\"request\":\"phone\",\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\"}"

I have content that I need in message data (token).

json_decode doesn’t work here, it returns {}

How to solve:
<?php
$s = "HTTP/1.1 200 OK\r\nDate: Mon, 16 Mar 2020 13:44:57 GMT\r\nContent-Type: application/json\r\nContent-Length: 369\r\nConnection: keep-alive\r\nx-amzn-RequestId: 9820238c-fe40-47dd-a848-3b2d01a929a2\r\nx-amz-apigw-id: JfFh7HBmrPEFrQw=\r\nX-Amzn-Trace-Id: Root=1-5e6f82d9-dff16fe84c4297a6aa2a3ce4;Sampled=0\r\n\r\n{\"ok\":true,\"request\":\"phone\",\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\"}";

$tmp = explode("\r\n", $s);
// output what we have
foreach($tmp as $row) {
   echo "$row\n";
}
// Detect the row we want
if ( substr($row,0,1) == '{' ) {
    $decoded = json_decode($row);
    echo "token: {$decoded->token}\n";
}

Results:

HTTP/1.1 200 OK
Date: Mon, 16 Mar 2020 13:44:57 GMT
Content-Type: application/json
Content-Length: 369
Connection: keep-alive
x-amzn-RequestId: 9820238c-fe40-47dd-a848-3b2d01a929a2
x-amz-apigw-id: JfFh7HBmrPEFrQw=
X-Amzn-Trace-Id: Root=1-5e6f82d9-dff16fe84c4297a6aa2a3ce4;Sampled=0

{"ok":true,"request":"phone","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."}
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.

Answer´╝Ü

From your original response data you posted …

The JSON String is a horrible mess. It is a JSON String inside a JSONString that also contains a newline delimited string. Hense the mess comment.

This will work, but it does assume you will always get the internal hidden JSON in the same occurance each time

$s = '{
"success": true,
"data": null,
"message": "HTTP/1.1 200 OK\r\nDate: Mon, 16 Mar 2020 12:50:37 GMT\r\nContent-Type: application/json\r\nContent-Length: 369\r\nConnection: keep-alive\r\nx-amzn-RequestId: 8eb61daa-145b-4e44-b0d1-137ee0bb9203\r\nx-amz-apigw-id: Je9kkGxFLPEFRbA=\r\nX-Amzn-Trace-Id: Root=1-5e6f761d-9c71b10297e40326ec764c9c;Sampled=0\r\n\r\n{\"ok\":true,\"request\":\"phone\",\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\"}"
}';

$j1 = json_decode($s);
$yuk = explode("\n", $j1->message);
$j2 = json_decode($yuk[9]);

echo $j2->token;

RESULT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Leave a Reply

Your email address will not be published. Required fields are marked *