1

I'm using PHP to take the inputs of an HTML form and add them to a JSON file like so:

$file = ('inputs');
      $array = array(
        'First Name' => $firstname,
        'Last Name' => $lastname,
        'Email' => $email,
   );

It worked initially but when I added multiple sets of data I was getting an "expected end of document" error in VS Code because I had to put [] tags around the data sets which are enclosed in {} tags.

// Example of JSON Data
[
       {
           "First Name": "James",
           "Last Name": "Smith",
           "Email": "[email protected]",
       }
]

When I add more data it adds the {} data outside of the [] tags and I have no idea how to fix it so that it goes within the [] tags, so I'm hoping someone here has some tips to help me out.

2

1 Answer 1

1

To put it in an array, just wrap an array around.

$array = ['First Name' => $firstname, 'Last Name' => $lastname, 'Email' => $email];
$array = [$array];

or just in one step

$array = [['First Name' => $firstname, 'Last Name' => $lastname, 'Email' => $email]];

To make it look nice, you can use the JSON_PRETTY_PRINT option

echo json_encode($array, JSON_PRETTY_PRINT);
[  
    {  
        "First Name": "James",  
        "Last Name": "Smith",  
        "Email": "[email protected]"  
    }  
] 
Sign up to request clarification or add additional context in comments.

2 Comments

This sort of works but when I add more data from the form it puts all of them outside within new [ ] tags and causes errors in the JSON file
@JU5TU5 Please edit the question and show your code, otherwise we can't say what's wrong with it. Is it possible you're concatenating several calls to json_encode()? Two JSON strings put together don't make JSON, just like you don't get a two story building by piling up two houses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.