Search code examples
phpjsoncurlresponse

PHP- Access json response data from curl


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 {}


Solution

  • <?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.