Formatting JSON in PHP - php

I am trying to build some JSON on the in PHP. I am brand new to PHP and know very little about it. Currently, I have the following:
$json = '{"content":{"person":{"name":"$name", "email":"$email"}, "title":"$subject", "description": { "body": "$details" }}}';
$name, $email, $subject, and $details are all variables that have been defined previously. If I print out $json using the code above, I get the following:
{"content":{"person":{"name":"$name", "email":"$email"}, "title":"$subject", "description": { "body": "$details" }}}'
In other words, my variables didn't replace the placeholders in the string. How do I build some JSON using variables as key values?
Thank you!

In PHP, double quotes and single quotes do different things; you can only use variables inline within strings if you use double quotes:
$test = 'world';
echo 'Hello $test!'; // Prints: Hello $test!
echo "Hello $test!"; // Prints: Hello world!
If you use double quotes to surround your json string, you'd need to escape all the double quotes that you have inside it:
$json = "{\"content\":{\"person\":{\"name\":\"$name\", \"email\":\"$email\"}, \"title\":\"$subject\", \"description\": { \"body\": \"$details\" }}}";
Alternative Method
NB: Are you familiar with PHP arrays? PHP has the function json_encode that converts arrays into JSON strings - doing that might make your code easier (especially if your json string is going to get larger / more complex at any point)
$json = json_encode(array
(
"content" => array
(
"person" => array
(
"name" => $name,
"email" => $email
),
"title" => $subject,
"description" => array
(
"body" => $details
)
)
));
Either of these solutions should give $json the value you expect
Hope this helps :) x

As mentioned in the comments, the best way would be to build up your data into the structure that you want and use json_encode to fix it.
The reason that you particular string is not replacing the variables is because it is enclosed by ' instead of "
$json = "{\"content\":{\"person\":{\"name\":\"$name\", \"email\":\"$email\"}, \"title\":\"$subject\", \"description\": { \"body\": \"$details\" }}}'\";
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

$content = json_encode(array(
'content' => array(
'person' => array(
'name' => $name,
'email' => $email,
'title' => $subject,
'description' => array(
'body' => $details
)
)
)
);
echo $content;

The documentation is always very helpful, check out the ones for strings, here it will explain how you can and cannot use variables in single quoted or double quoted strings.
Documentation on Strings
An easier solution is to use an array and json_encode it which will output what you have in your question:
<?php
$array = array(
'content' => array(
'person' => array(
'name' => $name,
'email' => $email,
),
'title' => $subject,
'description' => array(
'body' => $details,
),
),
);
$json = json_encode($array);

Related

Why is \r\n appearing when I JSON encode an array

I'm creating some arrays and turning them into JSON strings and I noticed something strange--some of the strings,
when I JSON encode them, are getting \r\n added onto the front and end of the of the strings.
The strings I'm encoding are pulled from HTML elements.
$arr = array(
'licStat' => $rows2[13]->nodeValue,
'expDate' => dateReplace($data[5]->nodeValue),
'dicAct' => $rows2[11]->nodeValue
);
echo json_encode($arr);
Expected output:
{"licStat":"Expired","expDate":"1999-12-20","dicAct":"Yes"}
Actual output:
{"licStat":"\r\n Expired\r\n ","expDate":"1999-12-20","dicAct":"\r\n Yes\r\n "}
It seems $rows2[13]->nodeValue and $rows2[11]->nodeValue have carry return and line feeds in them.
You can use trim() to get rid of them:
$arr = array(
'licStat' => trim($rows2[13]->nodeValue),
'expDate' => dateReplace($data[5]->nodeValue),
'dicAct' => trim($rows2[11]->nodeValue)
);
echo json_encode($arr);

Generate php array definition from JSON

My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.

PHP string convert to array

$paypal_details = "array (
'last_name' => 'Savani',
'item_name' => 'Description and pricing details here.',
'item_number' => '101',
'custom' => 'localhost',
'period' => '1',
'amount' => '10.01'
)";
Here is sample string in which contain full array.
Is this possible to convert string to array as it is?
You really should try to get the information in JSON or XML format instead, which both can be parsed natively by PHP. If that is not possible you can use the code snippet below to get a PHP array from the string. It uses regular expressions to turn the string into JSON format and then parses it using json_decode.
Improvements should of course be made to handle escaped single quotes within values etc., but it is a start.
$paypal_details = "array (
'last_name' => 'Savani',
'item_name' => 'Description and pricing details here.',
'item_number' => '101',
'custom' => 'localhost',
'period' => '1',
'amount' => '10.01'
)";
# Transform into JSON and parse into array
$array = json_decode(
preg_replace(
"/^\s*'(.*)' => '(.*)'/m", # Turn 'foo' => 'bar'
'"$1": "$2"', # into "foo": "bar"
preg_replace(
"/array \((.*)\)/s", # Turn array (...)
'{$1}', # into { ... }
$paypal_details
)
),
true
);
echo "Last name: " . $array["last_name"] . PHP_EOL;
Output:
Last name: Savani
You can use the explode() function.
<?php
$str = "Hello world. It's a beautiful day.";
print_r(explode(" ", $str));
http://www.w3schools.com/php/func_string_explode.asp

String to array conversion if string has content like an array

I have something like this:
array('fields' => array(
0 => array('name' => 'family_name',
'label' => 'Family Names'),
array('name' => given_names',
'label' => 'Given Names'),
array('name' => 'additional_names',
'label' => 'Additional Names'),
array('name' => 'honorific_prefixes',
'label' => 'Honorific Prefixes'),
array('name' => honorific_suffixes',
'label' => 'Honorific Suffixes')
)
)
in a variable as string. The whole thing is in one database field. If I output the variable, it is a string.
I would have an array with the content as subarrays. How do I convert this value into an array?
I searched with google, but I found explode and split and so on, but I think I miss the key word to find any solution.
Thank you for any help in this case.
Try using eval(), https://secure.php.net/manual/en/function.eval.php
eval("\$array = $string;");
print_r($array);
Your string is not built correctly to put it into the eval function. Two strings inside don't have the preceding quote and that will lead to a parse error. But you can correct it with:
$string = str_replace("=> given_names'", "=> 'given_names'", $string);
$string = str_replace("=> honorific_suffixes'", "=> 'honorific_suffixes'", $string);
After that you can use the answer of shapeshifter (please mark his answer as the correct one):
eval("\$array = $string;");
var_dump($array);
If you just look for a method to save and restore your arrays you could also use serialize / unserialize.

php array to json array (using sendgird)

I would like to use a php array in this example rather than have to hard code the array. How would I use a php to replace this json example?
Here the working code with the json array:
$json_string = array(
'to' => array(
'example1#sendgrid.com', 'example2#sendgrid.com'
),
'category' => 'test_category'
);
But I need to replace the 'to' values with my own php array. I tried this but it doesn't work:
$myEmails[] = array('emailOne#gmail.com','email2#gmail.com');
$json_string = array(
'to' => $myEmails, /// DOES NOT WORK
'category' => 'test_category'
);
What code for the json could I use to add my own php array values here? In short I am trying to send multiple emails using sendgrid but I thought this might work but its not.
Just get rid of the square braces [] after $myEmails, and everything should work:
<?php
$myEmails = array('emailOne#gmail.com','email2#gmail.com');
$json_string = array(
'to' => $myEmails, /// DOES NOT WORK
'category' => 'test_category'
);
var_dump($json_string);
?>

Categories