简体   繁体   中英

How to Read Amazon SNS JSON Response

How do I get the TranscriptionJobName and TranscriptionJobStatus from Amazon SNS's response to an http endpoint?

When I try my code below, the name variable in my text file is blank but the message from Amazon logs into my file.txt just fine.

What I get from SNS in the file.txt (some values omitted):

Array
(
    [Type] => Notification
    [MessageId] => MSG_ID
    [TopicArn] => TOPIC_ARN
    [Message] => {"version":"0","id":"msg_id","detail-type":"Transcribe Job State Change","source":"aws.transcribe","account":"account_number","time":"2019-03-07T18:19:08Z","region":"us-east-1","resources":[],"detail":{"TranscriptionJobName":"702edfc","TranscriptionJobStatus":"COMPLETED"}}
    [Timestamp] => 2019-03-07T18:19:09.194Z
    [SignatureVersion] => 1
    [Signature] => sign==
    [SigningCertURL] => sign_cert.pem
    [UnsubscribeURL] => unsubscribe_url
)

What I get from namer.txt:

{

My code is able to read the message sent to the endpoint but trying to parse further into the response returns blank in a txt file I'm using to debug..

My Code Attempt:

    //Endpoint.php

 //Fetch the raw POST body containing the message
    $postBody = file_get_contents('php://input');

    // JSON decode the body to an array of message data
    $message = json_decode($postBody, true);


    if ($message) {

    //just for debugging put entire response in file.txt
    file_put_contents('file.txt', print_r($message, true));


    //if its a Notification 

    if ($message['Type'] === 'Notification'){

     //then get the name of the Transcription Job 

        $name = $message['Message']['detail'][0]['TranscriptionJobName'];

    //put that into namer.txt
        file_put_contents('namer.txt', $name,true);






                                }

    }

For some reason, it seems like $message['Message'] still is a string and not an array.

You need to decode it before you can access elements in it:

// Decode
$message['Message'] = json_decode($message['Message'], true);

// Now you can access it using:
$name = $message['Message']['detail']['TranscriptionJobName']; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM