PHP funcions and Webservice returns - php

When I make a request to my webservice one time I get:
funcion login returns => {
"token":"fsuehfisubfibiefasasdapmwineq","client":"Admin","permission":"ADMIN"
}
And I can just save something like the client or the token in a variable, doing for example:
$json = login($email,$password); - saving the JSON in the variable $json.
$values = json_decode($json); - decoding the $json and saving it on $values.
And know if I want to save the name or the token for future requests to the webservice I make a variable:
$token = $values->{'token'};
$client = $values->{'client'};
But my question is what i do when i get this from the webservice, because I did the same and tried somethings and I'm not getting anywhere.
funcion member returns = {
"Table":[
{
"client":"Admin",
"name":"Martin Lupin",
"age":"25",
"city":"Lisbon"
}
]
}
How do I access to "client", "name", "age", "city"?
I tried to do:
$name = $valuesclient->{'client'}; - and nothing
$name = $valuesclient->{'table'}->{'client'}; - and nothing
$name = $valuesclient->{'table'->{'client'}}; - and nothing
Can someone help me?

Related

unable to store data from $request to mysql using Laravel 5.4

I am passing a POST request with 3 variables
Id (Randomly Generated),
Name (Specified)
Capacity (Specified)
from an Angular Service post. These are in the payload of the POST, and also visible in $request variable in the Laravel resource controller method "store()".
public function store(Request $request)
{
$servers = new Server();
return $request->getContent();
}
Here in Chrome's developer tool>network>POST request>on preview I get this
[{name: "bakar", capacity: 50, id: 8012}]
0: {name: "bakar", capacity: 50, id: 8012}
but when I use
public function store(Request $request)
{
$servers = new Server();
$data = $request->getContent();
$servers->id = $data->id;
$servers->name = $data->name;
$servers->capacity = $data->capacity;
$servers->save();
}
In the above method I got an error exception stating:
" Trying to get property of non-object "
How can I solve this?
Based on your JSON sample, $data should contain an array, which then contains a single object at its first index.
Therefore you cannot do e.g. $data->id because that's assuming that $data has a property called $id...it doesn't, the object at its first index does.
So simply $data[0]->id would allow you to access that index, and then access the $id property of the object at that index. Of course if your request contained multiple items in the array, you might need to use a loop to go through them all and get the values. It depends what you're expecting and what you intended to do with it.
Or, it may be the case that your PHP is correct, and it's your client which is sending the data in the wrong format. It's not clear what the desired outcome actually is.
Edit:
Since it appears that $data is still a JSON string when it arrives in your store() function, you need to decode it. So first write
$data = json_decode($request->getContent());
(instead of $data = $request->getContent();) and then proceed as above.
Complete sample:
public function store(Request $request)
{
$servers = new Server();
$data = json_decode($request->getContent());
$servers->id = $data[0]->id;
$servers->name = $data[0]->name;
$servers->capacity = $data[0]->capacity;
$servers->save();
}

JSON parsing - outputs NULL - PHP

I am querying a 3rd party service which outputs json.
$data = json_decode($result,true);
var_dump ($data);
$data holds this:
{"response":{"status":"OK","token":"hbapi:187089:586e655ed1f9c:nym2","dbg_info":{"instance":"53.bm-hbapi.prod.ams1","slave_hit":false,"db":"master","parent_dbg_info":{"instance":"64.bm-hbapi.prod.nym2","slave_hit":false,"db":"master","parent_dbg_info":{"instance":"45.bm-api.prod.nym2","slave_hit":false,"db":"master","time":664.07299041748,"version":"1.17","warnings":[],"slave_lag":0,"start_microtime":1483629917.8571},"awesomesauce_cache_used":false,"count_cache_used":false,"uuid":"39e1c17a-7fe4-58ac-9486-c4dd5bbf96a3","warnings":[],"time":1159.7349643707,"start_microtime":1483629917.7835,"version":"1.17.150","slave_lag":0,"output_term":"not_found"},"awesomesauce_cache_used":false,"count_cache_used":false,"uuid":"286ca4bc-6964-50ad-b241-ff9df1304278","warnings":[],"time":1347.2578525543,"start_microtime":1483629917.6534,"version":"1.17.150","slave_lag":0,"output_term":"not_found","master_instance":"64.bm-hbapi.prod.nym2","proxy":true,"master_time":1159.7349643707}}}
I am trying to get the token value.
I tried
$token = $data["response"][0]["token"];
I get NULL
I also tried
$token = $data['response'][0]['token'];
And I still get NULL.
I have looked at How can I access an array/object? and other threads - can't find the issue.
$token = $data["response"]["token"];
json:
{
"response": {
"status": "OK",
"token": "hbapi:187089:586e655ed1f9c:nym2",
"dbg_info": {
}
}
}
Why are you accessing the pos [0] if isn't an array?
Instead of that try to access to the desired parameter like this:
$token = $data["response"]["token"];
change $data['response'][0]['token']; to $data['response']['token'];
$data['response'] is, it doesnot have the 0 index.
{
"status": "OK",
"token": "hbapi:187089:586e655ed1f9c:nym2",
"dbg_info": {
}
$data is an object (not an array), so you can access response as a property of this object: $data->response.
response is again an object. etc..
For example status can be called like this: $data->response->status.
You can see what is an object and what is an array using this code:
print "<pre>";
var_dump($data);
So in your case, to get token:
$token = $data->response->token
In $data you still have json, so you should call json_decode($data) one more time.

Retrieving a guzzle JSON post with simple php

I'm trying to retrieve a result from a guzzle json post using simple php.
this is my function in file1.php EDITED this file is in a laravel 5.3 project
public function getPhotos($properties)
{
$codes = [];
foreach($properties as $property)
{
$codes[$property['codigo']] = $property['cod_filial'];
}
$client = new Client();
$response = $client->request('POST', 'http://local.app/file2.php', ['json' => \GuzzleHttp\json_encode($codes)]);
var_dump($response); exit;
}
and this is my file in a local url http://local.app/file2.php edited this file is in a project outside laravel and i have endpoint configured pointing.
<?php
$input = file_get_contents('php://input');;
$input = json_decode($input);
return $input;
Guzzle response is empty and i'm not figuring out what i'm doing wrong.
Can someone help me? Thanks a lot.
1) Try in your first file:
var_dump($response->getBody()->getContents());
// or
var_dump((string)$response->getBody());
2) Read the documentation about json option more carefully, this option accepts simple PHP array, you should not call json_encode manually.

How to correctly send data to json via php?

I am working with Mailchimp API, and trying to pass the user name from my form to the list.
Mailchimp has a nested structure for an actual user name, and I don't understand how to correctly write code for it.
The JSON data structure looks like that:
{
"email_address": xxx#xxx.com
"merge_fields": {
"FNAME":
"LNAME":
}
}
To send the post request the script using a function with post method
$result = $MailChimp->post("lists/$mailchimp_list_id/members", [
'email_address' => $subscriber_email,
'status' => 'subscribed',
//'merge_fields'['FNAME'] => $subscriber_name;
]);
I try to send 'merge_fields'['FNAME'] => $subscriber_name;
Can anyone explain me how to get inside the JSON with PHP?
Try like this
$jsonArray = json_encode(array('0' =>'test','1' => 'test2'));
json_encode will convert your php array to json format
If you want to decode your json array to php array then use json_decode
$phpArray = json_decode('Any json encoded array');
Okay, this is the best way to work with JSONs in PHP:
Add this to get the full JSON Body:
$json = file_get_contents('php://input');
Validate the json. I work with the Respect Validator.
https://github.com/Respect/Validation/blob/master/docs/Json.md
if(v::json()->validate($json)){
$whatever = new whatever($json);
}
Normalize the json object with a php class
class whatever{
public $email;
public $merged_fields;
function __construct($json){
$json = json_decode($json);
if($json->email){
$this->email = $json->email
}else{
echo "Error";
}
}
}
Use jsonSerializable for encoding. This is a really good HowTo:
http://www.sitepoint.com/use-jsonserializable-interface/
First create a PHP data structure to match the required JSON structure and then json_encode() that structure.
The {} means object in JSON
The [] means array in JSON
<?php
$inner = new stdClass();
$inner->FNAME = $subscriber_first_name;
$inner->LNAME = $subscriber_last_name;
$member = new stdClass();
$member->email_address = 'xxx#xxx.com';
$member->merge_fields = $inner;
$json_string = json_encode($member);

API Request $_POST returning empty array

I'm using Zurmo and trying to create a new account using REST API. I followed this documentation precisely: http://zurmo.org/wiki/rest-api-specification-accounts to pass the required parameters as json array.
This is my php code:
public function actionCreateOrUpdate()
{
$params=$_POST;
$modelClassName=$this->getModelName();
foreach ($params as $param)
{
if (!isset($param))
{
$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);
}
$r=$this->GetParam($param);
$res= array('status' => 'SUCCESS', 'data' => array($r));
print_r(json_encode($res,true));
}
}
function GetParam ($param){
$modelClassName=$this->getModelName();
if (isset($param['mobile_id'] ) && !$param['mobile_id']=='' &&!$param['mobile_id']==null)
{ $id=$param['mobile_id'];
$params=array();
foreach ($param as $k => $v) {
if(!($k=='mobile_id')) {
$params[$k] = $v;}
}
if ($params=null){$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);}
$tableName = $modelClassName::getTableName();
$beans = ZurmoRedBean::find($tableName, "mobile_id = '$id'");
if (count($beans) > 0)
{
$result = $this->processUpdate($id, $params);
}else{
$result = $this->processCreate($params,$id);
}
}
return $result;
}
The problem is that the $_POST method is returning an empty array. While debugging I tried to use print_r($_POST) and it also returned an empty array. I also tried to pass parameters as plain text and got the same result. I tried $_GET method and it worked. I think the problem is in the $_POST method, maybe I need to change something in my .php files. Any ideas please?
You should first hit the api with static data, to check if it works fine, then try to integrate php within that static data. You will need to read the documentation for which action accepts which format, and which method is supported(GET OR POST). Then try die(); , before sending if the array formed is as per the documentation.
I had similar issue when creating Account using REST API from java client. The problem was I did not send the proper POST request.
Another symptom also was on server side print_r(file_get_contents("php://input"),true); php code returned the correct request data.
Specifically the root cause was:
The Content-Type HTTP header was not "application/x-www-form-urlencoded"
The value field value in POST request was not properly encoded ( I used java.net.URLEncoder.encode method to overcome this)
After fixing these it worked.

Categories