Generate php array definition from JSON - php

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.

Related

How to convert JSON string to PHP object or array creation *code* [duplicate]

This question already has answers here:
print an array as code
(4 answers)
Closed 4 years ago.
FIRSTLY: This is a totally different question - How to convert JSON string to array
MY QUESTION...
I have a valid JSON string assigned to a php variable, $json.
I know that I can run it into json_decode($json, true); to parse into a php array at runtime, however I want to go a step beyond and convert this into a reusable php array code string, which can be simply copied and pasted into a php script, like $array = 'php array code here'.
For those who will inevitably ask "why?", an example:
to copy an example JSON endpoint parameter from an API's docs, then quickly convert to php array string code to paste into a test script as a valid test parameter for making a POST request
I know that I can do this:
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '<pre>';
echo '$phpArray = ' . print_r(json_decode($json));
echo '</pre>';
exit;
Which gets you close...
$phpArray = Array
(
[0] => stdClass Object
(
[ID] => 1
[Name] => Test One
)
[1] => stdClass Object
(
[ID] => 2
[Name] => Test Two
)
)
But there is of course still some work to do... currently I would copy this into Sublime Text or some other similar text manipulation tool and just use find/replace or regex find/replace in some cases. But what I am looking for is a quicker, more elegant solution whereby I could literally copy+paste that JSON into some script (or anywhere!), and run it to get this:
$phpArray = [
0 => [
'ID' => 1,
'Name' => 'Test One',
],
1 => [
'ID' => 2,
'Name' => 'Test Two',
],
];
Has someone created a good tool to do this already somewhere? I couldn't find anything. I am open to ANY elegant solution and will happily upvote any answer that is an improvement on this rudimentary means of bridging from the JSON to a PHP object / array creation code. Thanks!
<?php
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '$output = '.var_export(json_decode($json, true), true).';';
Output:
$output = array (
0 =>
array (
'ID' => '1',
'Name' => 'Test One',
),
1 =>
array (
'ID' => '2',
'Name' => 'Test Two',
),
);

Illegal string offset 'name' php - Many Array into 1 Array

With the help of variable categories i have this array in which all the arrays are without key/default index , because of this when i do $categories as $category in foreach and when i echo $category['name'] it gives illegal sting offet.
using laravel blade
What can be the possible solution for this or should i validate array first?
The above code is in JSON format, convert to array first
for example
$ex = {
'result':"success",
'categories':[{
//your rest of the code
}]
}
$data = json_decode($ex, TRUE);
//next use for each
foreach($data as $key => $value)
{
//rest of your logic
}
I think this is your situation, and in my opinion, you are using the wrong variable to decode let me take your image as an example here.
<?php
$ex = [
'result' => 'success',
'categories' => [
[
'id'=>1,
'name'=>'cat1',
],
[
'id'=>2,
'name'=>'cat21',
],
[
'id'=>3,
'name'=>'cat31',
],
]
];
echo "<pre>";
$res = json_encode($ex);
print_r(json_decode($res));
in this example, I just showed you that I have done json_encode and json_decode easily without any issue and the output of JSON is same as your example image.
Thank You!

Convert PHP to JSON with Nested Array

I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname#smsfree4all.com"
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);
This works fine. But what I am not sure about is how do I encode the properties in PHP with nested key value pairs shown below:
{
"username": "admin",
"password": "p4ssword",
"name": "Administrator",
"email": "admin#example.com",
"properties": {
"property": [
{
"#key": "console.rows_per_page",
"#value": "user-summary=8"
},
{
"#key": "console.order",
"#value": "session-summary=1"
}
]
}
}
What is this with # before key value?
Something like this should do it
$username="admin"; //more variables
$params=compact('username' /* more variables to be compacted here*/);
$params["properties"] = [
"property" => [
[
"#key" => "console.rows_per_page",
"#value"=> "user-summary=8"
],
[
"#key"=> "console.order",
"#value"=> "session-summary=1"
]
]
];
echo json_encode($params);
The manual has more examples you can use
Notice that:
A key~value array is encoded into an object
A regular array (array of arrays here) is encoded into an array
Those are all the rules you need to consider to encode any arbitrary object
Something like this perhaps?
$properties = [
'property' => [
['#key' => 'console.rows_per_page', '#value' => 'user-summary=8'],
['#key' => 'console.order', '#value' => 'session-summary=1']
]
];
It's difficult to tell what you're asking.
You can nest in PHP using simple arrays, very similar to JavaScript objects:
$grandparent = array(
"person1" => array(
"name" => "Jeff",
"children" => array(
array("name" => "Matt"),
array("name" => "Bob")
)
),
"person2" => array(
"name" => "Dillan",
"children" => array()
)
);

PHP & JSON: Inserting an array in a nested array

I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format

PHP json_encode() results showing JSONLint errors

I am having issues with validating the output of my json_encode() function.
I am pulling in an XML feed with cURL, converting it into an array, and converting that array into JSON with json_endode(). Ill spare you the cURL stuff:
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json = str_replace('\/','/',json_encode($article));
echo $json;
}
Which is giving me a JSON readout of:
{
"articleResult": {
"articleId": "0001",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
{
"articleResult": {
"articleId": "0002",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
This will give me a JSONLint error saying:
Parse error on line 10:
..._120x80.jpg" }}{ "articleResult
---------------------^
Expecting 'EOF', '}', ',', ']'
So naturally I will add in the comma, which gives me an End of File expectation:
Parse error on line 10:
..._120x80.jpg" }},{ "articleResu
---------------------^
Expecting 'EOF'
I am new to JSON, but I have checked the website and a few resources for proper JSON formatting and structure, and from what I can see my readout is following the guidelines. Any pointers?
Resources I've checked:
JSON.org naturally
Wikipedia has well documented page
W3Resource Had a good explanation of structure.
JSONLint
You were encoding 2+ objects into json string, you need [ ] to wrap them
the correct syntax is
[
{ /* first object */ }
, { /* second object */ }
, { /* third object */ }
]
the things you need to look out are
[ ] wrap
separate objects by comma
Solution
$json = array();
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json[] = $article;
}
echo json_encode($json);

Categories