Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive JSON payload with ZEND framework and / or PHP

I'm receiving a JSON payload from a webservice at my site's internal webpage at /asset/setjob. The following is the JSON payload being posted to /asset/setjob:

[{"job": {"source_filename": "beer-drinking-pig.mpg", "current_step": "waiting_for_file", "encoding_profile_id": "nil", "resolution": "nil", "status_url": "http://example.com/api/v1/jobs/1.json", "id": 1, "bitrate": "nil", "current_status": "waiting for file", "current_progress": "nil", "remote_id": "my-own-remote-id"}}]

This payload posts one time to this page. The page is not meant for viewing but parsing the JSON object for the id and current_status so that I can insert it into a database. I'm using Zend framework.

HOW DO I receive this payload in Zend? Do I $_GET['json']? $_POST['job']? None of these seem to work. I essentially need to assign this payload to a php variable so that I can then manipulate it.

I've tried:

$jsonStrGet = var_dump($_GET); $jsonStrPost = var_dump($_POST);

And I've tried: $response = $this->getResponse(); $body = $response->getBody();

Blockquote

Any help would be much appreciated! Thanks.

like image 514
kent3800 Avatar asked May 16 '10 06:05

kent3800


2 Answers

It is possible to get payload data this way (inside your action method):

$body = $this->getRequest()->getRawBody();
$data = Zend_Json::decode($body);

The $body will contain your raw JSON string: [{"job": {"source_filename": ...}] and $data variable will contain decoded JSON data passed in payload.

like image 153
ischenkodv Avatar answered Oct 20 '22 19:10

ischenkodv


Following up on what @Saeven said above for Zend Framework 2 you would have use $request->getContent() with \Zend\Json\Json::decode. Here's an example I used for testing.

<?php

namespace Rsvp\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;

class RsvpController extends AbstractActionController{

    public function getAccessTokenAction() {
        $request = $this->getRequest();

        $result = array('status' => 'error', 'message' => 'There was some error. Try again.', 'isXmlHTTP' => $request->isXmlHttpRequest());

        if($request->isXmlHttpRequest()){
             $data = \Zend\Json\Json::decode($request->getContent());

            if(isset($data->token) && !empty($data->token)){
                $result['status'] = 'success';
                $result['accessToken'] = '1234';
               $result['message'] = '';
            }
        }

        return new JsonModel($result);
    }
}
like image 33
tophstar Avatar answered Oct 20 '22 19:10

tophstar