dimanche 29 janvier 2017

How can I parse a JSON object in PHP? How can I retrieve the values of some specific fielnds of this JSON object?

I am absolutly new in PHP and moreover in Laravel framework (I don't know if Laravel provides some utility class for this kind of tasks). I came from Java.

So I have the following problem:

into a class I perform a call to a REST web service, something like this:

    $response = $client->get('http://localhost:8080/Extranet/login',
        [
            'auth' => [
                'dummy@gmail.com',
                'pswd'
            ]
        ]);

    $dettagliLogin = json_decode($response->getBody());

   \Log::info('response: '.(json_encode($dettagliLogin)));

$response->getBody() contains the returned JSON object, this is the output of the previous \Log::info():

{
    "id":5,
    "userName":"Dummy User",
    "email":"dummy@gmail.com",
    "enabled":true
} 

So I have the following problems:

1) What exactly returns the json_decode() function? I really can't understand because PHP is not strongly typed and I have not a declared return type.

This is the method signature:

function json_decode($json, $assoc = false, $depth = 512, $options = 0)

and in the related doc it says @return mixed. What exatly means mixed?

2) Anyway the main problem is: I have to use the content of the previous returned JSON object and put these value into the related field of an array like this:

$attributes = array(
    'id' => HERE THE id FIELD VALUE OF MY JSON OBJECT,
    'username' => HERE THE email FIELD VALUE OF MY JSON OBJECT',
    'name' => HERE THE userName FIELD VALUE OF MY JSON OBJECT,
    );

So I think that I have to parse the value of the $response->getBody() or of the json_decode($response->getBody()) to obtain these values. But how exactly can I do it? What is the neater way to do it? Laravel fframework provides some utility to do it?

Tnx



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2jGCk4X
via IFTTT

Aucun commentaire:

Enregistrer un commentaire