Pass Form PHP Variables to JSON Encode - php

I have a form with these values:
$firstName = strip_tags(trim($_POST['first-name']));
$lastName = strip_tags(trim($_POST['last-name']));
$email = filter_var(trim($_POST['user-email']),FILTER_SANITIZE_EMAIL);
I'm trying to pass these values onto this:
$request_body = json_decode('[{
"first_name" : "Tom",
"last_name" : "Hanks",
"email" : "example#gmail.com"
}]');
Tried saving the form values to an array and passing it into json_decode where $userArray are the form values, but not go. Example:
$request_body = json_decode($userArray, true);
All of this is to pass these form values into an API (SendGrid), but it's just not working for me and their documentation is not very descriptive. I guess they want a specific request format. Here's an example of their request body from their Github page. I can have these values hard coded in and it works fine, but the idea is for the form to pass in these user name and email values automatically.
$request_body = json_decode('[
{
"age": 25,
"email": "example#example.com",
"first_name": "",
"last_name": "User"
},
{
"age": 25,
"email": "example2#example.com",
"first_name": "Example",
"last_name": "User"
}
]');
Any ideas what I'm doing wrong? Thanks!

The way you sent your post :
$array[0]['email'] = filter_var(trim($_POST['user-email']),FILTER_SANITIZE_EMAIL);
$array[0]['first_name'] = strip_tags(trim($_POST['first-name']));
$array[0]['last_name'] = strip_tags(trim($_POST['last-name']));
echo json_encode($array);
Result :
[{"email":"john.doe#exemple.com","first_name":"John","last_name":"Doe"}]
The [0] might have been an issue, it produce the "[" "]" when you read the json_decode output and reproduce the exact same array when decoded with json_decode.
So if their script is looking for integers as keys, if you omit the [0], they will get an array in the following format $array['email'] etc. This might be an issue.
If you would like to reproduce that in a loop and send multiple entries at once
you could write it this way instead :
$array[] = array('email' => filter_var(trim($_POST['user-email']),FILTER_SANITIZE_EMAIL),
'first_name' => strip_tags(trim($_POST['first-name'])),
'last_name' => strip_tags(trim($_POST['last-name']))
);
You will still be missing the "age". Make sure it is not a mandatory field!

I think you might be getting a little confused while using json_decode() and json_encode().
json_encode() encodes a PHP array into a JSON array.
Whereas json_decode() decodes a JSON array back into a PHP array.
In regards to your situation the following should produce the same output:
$array = array(
"first_name" => "Tom",
"last_name" => "Hanks",
"email" => "example#gmail.com"
);
echo json_encode($array);
Produces:
{"first_name":"Tom","last_name":"Hanks","email":"example#gmail.com"}
Using these functions to build the array then encode/decode to/from JSON is far better than manually creating the JSON array. As this avoids any syntax errors that you may create.
Hope this helps.

Related

Problem with json_encode() it removes the "0" key from JSON string number in PHP

I need to call this value registered in a MySQL column:
{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}
With this form I get the JSON from the MySQL database:
$boosterResultant = $mysqli->query('SELECT boosters FROM player_equipment WHERE userId = '.$player['userId'].'')->fetch_assoc()['boosters']; //response: "{\"0\":[{\"Type\":3,\"Seconds\":-185}],\"1\":[{\"Type\":4,\"Seconds\":-144}]}"
I want to access what is in 'Seconds' to modify its value, so I use this form to modify it:
$boosterFinal = json_decode($boosterResultant,true);
$boosterFinal[0][0]['Seconds'] += 36000; //the value is changed successfully
echo "Output:", json_encode($boosterFinal); //out: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]]
Since I run $boosterFinal = json_decode($boosterResultant,true); I get this: [[{"Type":3,"Seconds":-185}],[{"Type":4,"Seconds":-144}]]
but I need to stay like this for update later in the DB:
{"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]} //good
//bad: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]]
Edit: Thanks to #A. Cedano (link of answer in Spanish forum: here), I found the answer:
//This is the data that comes from the sample DB
$str='{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}';
//Don't pass TRUE to json_decode to work as JSON as is
$mJson=json_decode($str);
$mJson->{0}[0]->Seconds+=36000;
//Object Test
echo $mJson; //Output: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]}
If PHP sees that your array keys are ascending ints, it automatically converts them into an array (php.net/manual/en/function.json-encode.php)
You can disable this by passing the JSON_FORCE_OBJECT flag as a second param into json_encode: json_encode($boosterFinal, JSON_FORCE_OBJECT)
I had a similar problem, where JSON_FORCE_OBJECT didn't work. I had an array that looked like this:
<?php
$array = [
"someKey" => [
0 => "Some text....",
1 => "Some other text....."
]
];
Using json_encode with no flags I got a JSON object that looked like this:
{
"someKey": [
["Some text...."],
{"1": "Some other text....."}
]
}
This is clearly not what I had as the PHP object, and not what I want as the JSON object.
with the JSON_FORCE_OBJECT I got a JSON object that looked like this:
{
"someKey": [
{"0": "Some text...."},
{"1": "Some other text....."}
]
}
Which does fix the issuse I had, but causes another issue. It would add unnecessary keys to arrays that don't have keys. Like this:
$array = ["Sometext..."];
echo json_encode($array, JSON_PRETTY_PRINT|JSON_FORCE_OBJECT);
// {0: "Sometext..."}
We once again have the same issue, that the JSON object is not the same as the original PHP array.
Solution:
I used stdClass for the array that had numeric keys. and It encoded it to JSON correctly. code:
$array = [];
$stdClass = new stdClass();
$stdClass->{0} = "Some text...";
$stdClass->{1} = "Some other text....";
array_push($array, ["someKey" => $stdClass]);
$json = json_encode($array, JSON_PRETTY_PRINT);
echo $json;
//Output:
/*
{
"someKey": [
{"0": "Some text...."},
{"1": "Some other text....."}
]
}
*/
This is because PHP does not touch the indexes when encoding an stdClass.

PHP Only Returning Last JSON Object

I'm attempting to do something I've done many times before (access objects in a JSON file with PHP) and for some reason json_decode is only returning the last item in the JSON array. Here's the JSON:
{
"person": {
"lname": "smith",
"fname": "bob"
},
"person": {
"lname": "jones",
"fname": "jane"
}
}
And the PHP:
<?php
//access and dump
$json = file_get_contents('people.json');
$filey = json_decode($json, true);
var_dump($filey);
?>
The result is only the last item in the array:
array (size=1)
'person' =>
array (size=2)
'lname' => string 'jones' (length=5)
'fname' => string 'jane' (length=4)
Using json_last_error returns no errors and I'm valid according to jsonlint. I'm also not finding any console errors when I load the page.
I'm totally stumped and can't see anything different from the times I've done this before - can anyone identify what I'm missing here?
That's because your json object names "person" within json array are similar so json decode will override the values with latest.
Consider something like
{
"person1": {
"lname": "smith",
"fname": "bob"
},
"person2": {
"lname": "jones",
"fname": "jane"
}
}
and your code will work fine.
Marcatectura, I know you've already accepted the answer that suggests using different object keys but I thought you should know. If you want an array in PHP, You don't even need object names. The following JSON will do:
[
{
"lname": "Dawes",
"fname": "April"
},
{
"lname": "Colin",
"fname": "Dick"
}
]
A trick I use when I'm designing my JSON is to build a sample PHP array in the shape I want json_decode to give me, encode that array and output the result to screen. So what I posted above is the result of:
$arr = [
['lname'=>'Dawes','fname'=>'April'],['lname'=>'Colin','fname'=>'Dick'],
];
$json = json_encode($arr);
echo $json;
Since I built a JSON by encoding an array having the shape I want, I can be confident that even as my data change, json_decode($json,true) will give me the array shape I expect.
Happy coding.
When you use json_decode(true), your json is now an array.
You cannot have two array keys that are the same, in this case "person".
If you still want to use json_decode(true), then change "person" to "person1" or so.
Try both var_dump($filey) and var_dump($json), you will see what I'm talking about.

Accessing value inside multi-dimension JSON array using PHP

I read several posts on here and have been unable to find success in resolving the problem I am having.
I am trying to figure out how to get the NAME field from the UploadImage array.
I have the following JSON being passed to me from a Webhook.
{
"$version":5,
"Entry":{
"Number":"11",
"Order":null,
"Origin":
{
"City":"Portland",
"CountryCode":"US",
}
,
"Message":"the message",
"UploadImage":[
{
"ContentType":"image/png",
"Id":"F-lMbiCYdwiYS8ppkQS4gsyE",
"Name":"Screen.png",
"Size":55907
}
],
"Subject":"here is the subject"
}
I have no problem grabbing the value of Subject or Message, but I cannot figure out how to grab the NAME within UploadImage.
$contact = json_decode($json);
$subject=$contact->{'Subject'};
When I do
$uploadimage=$contact->{'UploadImage'};
it just writes out ARRAY.
I can do
echo $contact->{'Entry'}->{'Number'};
and it works, so it has to be something with the bracket being there before the curly bracket. I know this has to be something simple that I am missing.
Any help is GREATLY appreciated.
$uploadimage=$contact->{'UploadImage'}[0]->{'Name'};
Firstly try
$contact = json_decode($json, true);
Adding the second argument returns an array instead of an object which will make things easier. Objects with numerical keys are troublesome... Now you can,
print_r($contact);
to see exactly what you've got. I imagine that
echo $contact['UploadImage'][0]['Name'];
Will get you what you're looking for.
Notice that UploadImage contains an array of objects (or an array of arrays after conversion).
another solution is:
$contact = json_decode($text);
$name = '';
foreach($contact->UploadImage as $k=>$v){
foreach($v as $k2=>$v2){
echo $k2.' - '.$v2.'<br />';
if($k2=='Name'){ $name = $v2;}
}
};
var_dump($name);
//response
ContentType - image/png
Id - F-lMbiCYdwiYS8ppkQS4gsyE
Name - Screen.png
Size - 55907
//name
string 'Screen.png' (length=10)
Have you try to use like below:
$uploadimage=$contact->UploadImage[0]->Name;
In JSON the square braces [] mark an array section and the curly braces {} mark an object. In your JSON string UploadImage is an array, which contains a single object.
Try changing your JSON as follows:
{
"$version": 5,
"Entry": {
"Number": "11",
"Order": null,
"Origin": {
"City": "Portland",
"CountryCode": "US"
},
"Message": "the message",
"UploadImage": {
"ContentType": "image/png",
"Id": "F-lMbiCYdwiYS8ppkQS4gsyE",
"Name": "Screen.png",
"Size": 55907
},
"Subject": "here is the subject"
}
}

How to create a JSON array in php?

I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks
If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.
No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.

Parse json array without value in php

I wonder how to parse a json array without values
Json: {"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}
How can i get the value of email in a foreach loop?
What i mean with "without value" is: there is an array called email and name... How can i get the value for "email" that currently says NOT_UNIQUE?
In your current example, your JSON string is malformed. I dont know if thats a typo on your part while creating your question. Assuming the JSON string is okay in your code, a simple json_decode() will do just fine. Consider this example:
$json_string = '{ "Json": { "status": "FAILED", "errors": { "email": [ "NOT_UNIQUE" ], "name": [ "TOO_SHORT" ] } }}';
$data = json_decode($json_string, true);
echo $data['Json']['errors']['email'][0]; // NOT UNIQUE
use json_decode, json_decode($str, true) will return it as an assosiative array whereas json_decode($str, false) will return objects.
json_decode("{"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}", true)['errors']['email']
should get the email for you.

Categories