Sitemap / Advertise

Information



Tags



Share

How to create a JSON file and upload it automatically to the client-server in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement


Banggood
Banggood


Definition

In this tutorial, I will show you how to create a JSON file with a given string and upload the file to the client-server automatically without needing to click a classic verification button in PHP.

You can inspect a web application named JSON File Creator, that utilizes the same method, from the link below. Please sign in before inspecting the mentioned application.

Go to JSON File Creator.

Introducing JSON(1)

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { left brace and ends with } right brace. Each name is followed by : colon and the name/value pairs are separated by , comma.

An array is an ordered collection of values. An array begins with [ left bracket and ends with ] right bracket. Values are separated by , comma.

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

Code

Syntax:

main_object_name:name_1_1=value_1_1,name_1_2=value_1_2;name_2_1=value_2_1,name_2_2=value_2_2/...

Create a function named JSON_File_Creator with two parameter - data string and file name.

Using the explode() function, split the data string to find every main object.

For each main object (seperated by '/'):

Define add and new line arrays.

Get the main object's name and variables.

For each object in the main object (seperated by ';'):

Using the explode() function, split every variable that of the current object (seperated by ',').

For each variable:

Get the name of the variable and the value of the variable.

Add the new variable to the new line array with its name.

Using the array_push() function, add the new line array including the variables of the current object to the add array as a new array member.

Blank the new line array.

With the main object name, add the add array to the content array.

Open a file named as the predefined file name.

Using the json_encode() function, convert the content array to the JSON format and write the encoded array to the recently created file.

Close the file.

Define the file headers.

Upload the file to the client-server by executing the readfile() function.

To prevent user disruption, use the ignore_user_abort(true) function.

To delete the file, use the unlink() function.

Define the content array and the data string.

Note: To avert the Undefined Offset 1 error when using the explode() function, add the given delimiter to the end of the string ("$string[delimiter]").


<?php
function JSON_File_Creator($data_string, $file_name){
	$data = explode("/", $data_string);
	forEach($data as $main_string){
		$add = [];
		$new_line = [];
        $object_name = explode(":", $main_string)[0];
        $object_values = explode(":", "$main_string:")[1];
		
		forEach(explode(";", $object_values) as $objects){
			$object_variables = explode(",", $objects);
			forEach($object_variables as $new_variable){
				$name = explode("=", $new_variable)[0];
				$value = explode("=", "$new_variable=")[1];
				$new_line[$name] = $value;
			}
			
			array_push($add, $new_line);
			$new_line = [];
		}
		
		$content[$object_name] = $add;
	}
	
	$file = fopen($file_name, 'w');
    fwrite($file, json_encode($content));
	fclose($file);
		
    header('Content-Description: JSON File Creator');
    header('Content-Type: application/json');
    header('Content-Length: ' . filesize($file_name));
    header('Content-Disposition: attachment; filename="'.$file_name);
    readfile($file_name);
		
	ignore_user_abort(true);
	unlink($file_name);
	exit();
}

$content = [];
$string = "test:test=test,test=test;new=new,new=new/Books:id=001,name=To Kill a Mockingbird,author=Harper Lee;id=002,name=The Count of Monte Cristo,author=Alexandre Dumas;id=003,name=The Secret Life of Bees,author=Sue Monk Kidd";
JSON_File_Creator($string, "test.json");

?>

Result:

References

(1) https://www.json.org/json-en.html