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);
Related
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?
I want to test my API function by sending array of objects via postman
When I send my request in JSON format to the function and then looping through the array to access each object property it gives me the following error:
https://i.imgur.com/QV9MDsm.jpg
Here is my request:
https://i.imgur.com/4584wf3.jpg
I searched how to send an array of objects using postman and found that I am doing it the right way
I selected row under body section so I can add my request body and selected it's format as JSON and added "Content-Type: application/json" to the request header
My API function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine->machineNo;
$newMachine->account_type = $machine->accountType;
$newMachine->machine_type = $machine->machineType;
$newMachine->retialer_id = $retailer->retailerId;
$newMachine->save();
}
}
I expect that i can access each array object properties as a PHP object but I found that it is not an object by testing it using is_object() function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
return response()->json(is_object($machine));
}
}
I do not know if the problem is within my request or something that I might misunderstand while retrieving data of the request in my controller function
Either it is an array and in that case, you can call
$object = (object) $machine;
Or it is a string aka JSON, you can call
$object = json_decode($machine);
Or if it is an object/array use
$machine['machineType'];
Also please add a dump of the $machine var
EDIT
Try sending the request not using [] because they will be converted into an array with objects in it, instead, if you remove the [] and only have {} it should only be one object in the request
"machineInfo" : {
"machineNo" : "1123213",
"accountType" : "Paid",
//...rest here..
}
Try this:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$object = (object) $machine;
return response()->json(is_object($object));
}
}
Since your request sends data as an array, you can access the elements as so :
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine['machineNo'];
$newMachine->account_type = $machine['accountType'];
$newMachine->machine_type = $machine->['machineType'];
$newMachine->retialer_id = $retailer->['retailerId'];
$newMachine->save();
}
}
I am using the codeigniter rest by phil sturgeon.
I want to return a JSON object that contains another JSON object within.
My code looks like this
function volunteer_get()
{
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
$this->load->model('user/users_model');
$user = $this->users_model->get( $this->get('id') );
$address = $this->address_model->getAddress( $this->get('id') );
$user->address = $address;
$userJson = json_encode($user);
var_dump($userJson);
/*if($user && $user->auth_level == 1)
{
$this->response($userJson, 200); // 200 being the HTTP response code
}
else
{
$this->response(NULL, 404);
}*/
}
It is not showing any result... If i do this without adding the php object in the other php object, it shows me the json!
D:\wamp\www\codeigniter\application\controllers\api\Users.php:37:string '{"user_id":"1","username":"abc","email":"abc","auth_level":"1","banned":null,"passwd":"abcdefg","passwd_recovery_code":"abcdefg","passwd_recovery_date":"2017-06-12 18:50:31","passwd_modified_at":"2016-11-18 21:20:30","last_login":"2017-08-30 15:10:36","created_at":"2016-09-02 12:01:46","modified_at":"2017-08-30 15:22:45","first_name":"aze","family_name":"'... (length=1354)
In general, you need to check whether you got a JSON object (usually a PHP dictionary or object) or a JSON representation (a string).
You can not add a string to another string. And if you add a string to a dictionary or object, it won't be properly encoded as a JSON sub-object because it is, well, a string.
So if you have a representation, you have to decode it first:
// Here, $dataOne is a string, and $dataTwo is too.
// we decode to array rather than to object (see manual for json_encode)
$dataOneJSON = json_decode($dataOne, true);
$dataTwoJSON = json_decode($dataTwo, true);
$dataOneJSON['two'] = $dataTwoJSON;
$result = json_encode($dataOneJSON);
$this->response($result, 200);
I am a newbie. I am trying to make some experience about REST applications in PHP. So I receive (POST) a JSON body and store the value in my database. I just want to make a check if the JSON body I get is in the right way, if it matches the particular schema I set. I need something like this (for example):
my schema:
{"id":"int",
"name":"string",
"value":"double"
}
I just want to check that my JSON body contains the same fields and types. Thanks in advance.
UPDATE
Thanks to all for your answers. I'd like to follow krichprollsch's answer. It's exactly what I need. So I am using Ubuntu 12.04 LTS and NGINX server. I only installed HttpFoundation and Validator components via Composer. Now in my "www" folder I have a folder called "vendor" where Symfony's components are (I don't know if this folder has to be there). In order to check I made a script taken from some examples on the web but I've got a "500 Internal Server Error". The script is this:
<?php
require 'vendor/autoload.php';
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Lenght;
class user{
public function utente(){
$validator = Validation::createValidator();
$violations = $validator->validateValue('Bernhard', new Lenght(array('min'=>10)));
echo $violations;
}
}
$a = new user;
$a->utente();
?>
Any suggestions? Thanks
You can use the Symfony Validator component to validate the data from the json according with your schema : http://symfony.com/doc/master/book/validation.html
<?php
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
//...
$collectionConstraint = new Assert\Collection(
array(
'id' => new Assert\Type(array('type'=>'integer')),
'name' => new Assert\Type(array('type'=>'string')),
'value' => new Assert\Type(array('type'=>'double'))
)
);
//...
$data = json_decode($your_json);
$validator = Validation::createValidator();
$errorList = $validator->validateValue($data, $collectionConstraint);
Using Symfony validator allow you to check complex constraints, not only type of data.
You can also directly validate an hydrated object. Useful if you want to insert into database.
You want chek value???
YOu can decode json strings with json_decode() function.
For example:
$json = {"id":"int",
"name":"string",
"value":"double"
};
$decode = json_decode($json);
if($decode->value == 'Your value') {
//your code
} else {
echo 'Incorerct!';
}
Hey You can decode you json by php
using json_decode function
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array1 = json_decode($json, true);// it will return an array
for more about json_decode http://in2.php.net/json_decode
and can compare your data structure array ($array2) with this array
by intersecting them.
$result = array_intersect($array1, $array2);
print_r($result);
You can use json_decode to check if it is a valid syntax
$json = '{"id":"int",
"name":"string",
"value":"double"
}';
$decoded = json_decode($json, true);
if($decoded == null){
//your error message
echo "Error in JSON Format";
}
if the string is not valid, json_decode will return a null value
I want to create a more complex JSON Array where a customer (which has a name) has many phonenumbers so that i can parse it in PHP and i need your help.
i.e.:
public Class ContactVO
{
public String diplayname;
public ArrayList<PhoneVO> phonenumbers = new ArrayList<PhoneVO>();
}
public Class PhoneVO
{
public String number;
}
Can s.o. give me an example how to create the above 1:N structure as JSON Array and how to parse it via PHP?
I put everything in a ArrayList and added the GSON library to may project.
The result is:
[
{"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},
{"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
{"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
{"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
{"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]
How should the receiving PHP File lookslike to parse that?
Are you just looking for the json_decode function?
$fromPost = $_POST['contact'];
$object = json_decode($fromPost, true); // Read the doc to decide whether you want the "true" or not
var_dump($object);
Edit:
You could have something like that (not tested)
$string = '[
{"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},
{"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
{"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
{"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
{"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]';
$decoded = json_decode($string);
foreach($decoded as $person) {
echo $person['displayname'] . "\n";
foreach($person['phonenumbers'] as $phone) {
echo $phone['number'] . "\n";
}
}