Php arrays for json

PHP Json_encode: Serialize PHP Objects to JSON

PHP is a server-side scripting language for creating your website’s backend system that can serve webpages, communicate with databases, and exchange data over the internet. A decent backend framework like PHP needs to be capable of providing and processing data in any format (e.g., XML, JSON, etc.) to be socially accepted in a society of skilled web development frameworks.

Since JSON is a ubiquitous data format for sharing and storing data, it is vital that a PHP backend allows processing of JSON data. This is where json_encode (and json_decode) come into the picture and enable PHP processed data to be compatible with frameworks and systems that deal with JSON data and make way for easier and faster web development.

In this post, we’ll learn about the JSON format, about the json_encode() function — what it is, why it is required, and how it can be used to convert PHP data structures into JSON format, all with examples. In the end, we’ll also see how we can decode JSON data to be able to process it. Let’s get started!

Читайте также:  Нет java в дополнениях

Use these links to navigate the guide:

What is the JSON_Encode Function?

What is JSON?

JSON (JavaScript Object Notation) is one of the most popular open-standard file formats used for storing and sharing data. It uses human-readable text to represent data using attribute-value pairs and array data types.

This is what a common JSON object looks like —

We’ll be using this example in the sections below to understand how we can encode PHP data into JSON format.

JSON allows us to represent and encapsulate complex data in an organized fashion that can be shared easily across the internet. Even though JSON derives its name from JavaScript, JSON was created to be used by all programming languages.

Let’s see how we can convert our PHP variables into JSON format.

JSON_Encode — PHP variables to JSON

json_encode() is a native PHP function that allows you to convert PHP data into the JSON format.

json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string 

The function takes in a PHP object ($value) and returns a JSON string (or False if the operation fails). Don’t worry about the $options and $depth parameters; you’re seldom going to need them.

Let’s look at a simple example —

 1, 'b' => 2); echo json_encode($arr); ?>

Why encode to JSON?

As we saw above, JSON is one of the most common formats for exchanging data over the internet. Therefore, it can be imperative in some cases for PHP servers to provide JSON-encoded data and to be able to process it.

Let’s see how we can encode various PHP data structures into JSON using json_encode() .

Convert PHP Strings to JSON

JSON encoding for a string is the string itself. Therefore, encoding a PHP string into JSON is quite simple; it results in the same string being returned.

Let’s see this using an example —

PHP String to JSON Example

Convert PHP Objects to JSON

Since the information in JSON is stored in key/value pairs, json_encode() is more likely to be used to encode PHP objects and their instance variables.

PHP Object to JSON Example

Let’s understand how we can JSON-encode a PHP object by creating an instance of a Book class based on the Library example we saw above (Sec 1.1). We’ll create two instance variables for the book’s instance and encode the object using json_encode().

 $book = new Book(); $book->id = 101; $book->label = "Lorem ipsum"; $jsonData = json_encode($book); echo $jsonData."\n"; ?>

Convert PHP Array to JSON

There are three types of arrays in PHP, namely — Indexed arrays, Associative arrays, and Multidimensional arrays. Let us look at what these are and some examples of how we can encode each of these into JSON —

Indexed Array to JSON

Indexed arrays are conventional arrays that are represented by index numbers.

Example: $arr = array(1,2,3,4); // [1,2,3,4]

Converting them to JSON is quite easy —

Associative Array to JSON

Associative arrays are arrays that use named keys as indices for your values.

Example: $age = array(«John»=>»11», «Ken»=>»19», «Tim»=>»14»);

We can also arrive at the book JSON object that we saw above by encoding an Associative array as such —

101, "label"=>"Lorem Ipsum"); echo json_encode($book); ?>

Notice how an Indexed array is represented by an array in JSON, whereas Associative arrays take the form of a complete JSON object after being encoded.

Multidimensional Array to JSON

Multidimensional arrays can be created by nesting arrays into each other as such-

$multid_arr = array( array(1,2,3,4), array(1,2,3,4), ); 

We can create a Multidimensional array to store a list of books for our library example. Let’s create one and encode that into JSON.

101, "label"=>"Lorem Ipsum"), array("id"=>102, "label"=>"Dolor sir amet"), array("id"=>103, "label"=>"Lorem Ipsum dolor"), ); echo json_encode($books); ?>

Putting it all together

Now that we have seen how json_encode( ) is used in different contexts, for encoding different PHP data types, let’s put all of our learnings together to create JSON data for the Library example we saw above.

 class Library < >class Book < >$book1 = new Book(); $book1->id = 101; $book1->label = "Lorem ipsum"; $book2 = new Book(); $book2->id = 102; $book2->label = "Dolor sir amet"; $books = array($book1, $book2); $library = new Library(); $library->books = $books; $myClass = new MyClass(); $myClass->library = $library; $jsonData = json_encode($myClass); echo $jsonData."\n"; 

Well, that was fun! Now before we wrap up, I think it’s worthwhile to see how we can convert JSON data back to PHP variables.

JSON_Decode — JSON to PHP variables

In the very likely case of your JavaScript front-end sending JSON-based data back to your PHP server, you would need a way to decode the JSON data in a way that can be processed by PHP.

We can use PHP’s json_decode() function for the same, which takes in a JSON encoded string and returns the corresponding PHP variable.

json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed

$assoc parameter (False by default) is used to specify whether you need the function to return an Associative array or a standard class Object.

JSON_Decode example

Let’s try to retrieve the book object that we encoded into JSON above by decoding it using php_decode() .

'; $book = json_decode($book_json); var_dump($book); ?>

Note how by default a stdClass object is returned. For decoding it as an Associative array, set the $assoc parameter to True as such —

$book = json_decode($book_json, True);

This will result in an Associative array being returned.

Try the JSON_Encode Function for Yourself

In this post, we read about the JSON (JavaScript Object Notation) format, why it is essential, and how we can convert different PHP variables into JSON using json_encode() . We also saw how we could use json_decode() to decode JSON data into PHP variables. With this understanding of processing JSON data using PHP, go ahead and encode your PHP objects into JSON and share them across the internet. All of this while staying at home. Stay healthy, stay safe!

Get peace of mind knowing your PHP application is performing at its best with ScoutAPM

Follow Us on Social Media!

Источник

How to create an array for JSON using PHP?

In this article, we will see how to create an array for the JSON in PHP, & will see its implementation through examples.

Array: Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. An array is created using an array() function in PHP. There are 3 types of array in PHP that are listed below:

  • Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value.
  • Associative Array: It is used to store key-value pairs.
  • Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays.

For this purpose, we will use an associative array that uses a key-value type structure for storing data. These keys will be a string or an integer which will be used as an index to search the corresponding value in the array. The json_encode() function is used to convert the value of the array into JSON. This function is added in from PHP5. Also, you can make more nesting of arrays as per your requirement. You can also create an array of array of objects with this function. As in JSON, everything is stored as a key-value pair we will convert these key-value pairs of PHP arrays to JSON which can be used to send the response from the REST API server.

Example 1: The below example is to convert an array into JSON.

Источник

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар . Значение может быть массивом, числом, строкой и булевым значением.

В PHP поддержка JSON появилась с версии 5.2.0 и работает только с кодировкой UTF-8.

Кодирование

json_encode($value, $options) – кодирует массив или объект в JSON.

$array = array( '1' => 'Значение 1', '2' => 'Значение 2', '3' => 'Значение 3', '4' => 'Значение 4', '5' => 'Значение 5' ); $json = json_encode($array); echo $json;

Как видно кириллица кодируется, исправляется это добавлением опции JSON_UNESCAPED_UNICODE .

$json = json_encode($array, JSON_UNESCAPED_UNICODE); echo $json;

Далее такую строку можно сохранить в файл, или отдать в браузер, например при AJAX запросах.

header('Content-Type: application/json'); echo $json; exit();

Декодирование

Функция json_decode($json) преобразует строку в объект:

$json = ''; $array = json_decode($json); print_r($array);
stdClass Object ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )

Если добавить вторым аргументом true , то произойдёт преобразование в массив:

$json = ''; $array = json_decode($json, true); print_r($array);
Array ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )

Получение ошибок и их исправление

json_decode() возвращает NULL , если в объекте есть ошибки, посмотреть их можно с помощью функции json_last_error() :

$json = ''; $array = json_decode($json, true); switch (json_last_error())

Посмотреть значения констант JSON:

$constants = get_defined_constants(true); foreach ($constants['json'] as $name => $value) < echo $name . ': ' . $value . '
'; >
JSON_HEX_TAG: 1 JSON_HEX_AMP: 2 JSON_HEX_APOS: 4 JSON_HEX_QUOT: 8 JSON_FORCE_OBJECT: 16 JSON_NUMERIC_CHECK: 32 JSON_UNESCAPED_SLASHES: 64 JSON_PRETTY_PRINT: 128 JSON_UNESCAPED_UNICODE: 256 JSON_PARTIAL_OUTPUT_ON_ERROR: 512 JSON_PRESERVE_ZERO_FRACTION: 1024 JSON_UNESCAPED_LINE_TERMINATORS: 2048 JSON_OBJECT_AS_ARRAY: 1 JSON_BIGINT_AS_STRING: 2 JSON_ERROR_NONE: 0 JSON_ERROR_DEPTH: 1 JSON_ERROR_STATE_MISMATCH: 2 JSON_ERROR_CTRL_CHAR: 3 JSON_ERROR_SYNTAX: 4 JSON_ERROR_UTF8: 5 JSON_ERROR_RECURSION: 6 JSON_ERROR_INF_OR_NAN: 7 JSON_ERROR_UNSUPPORTED_TYPE: 8 JSON_ERROR_INVALID_PROPERTY_NAME: 9 JSON_ERROR_UTF16: 10

Если вы хотите распарсить JS объект из HTML страницы или файла, то скорее всего json_decode вернет ошибку т.к. в коде будут управляющие символы или BOM. Удалить их можно следующим образом:

$json = ''; // Удаление управляющих символов for ($i = 0; $i // Удаление символа Delete $json = str_replace(chr(127), '', $json); // Удаление BOM if (0 === strpos(bin2hex($json), 'efbbbf')) < $json = substr($json, 3); >$res = json_decode($json, true); print_r($res);

HTTP-запросы в формате JSON

Некоторые сервисы требуют чтобы запросы к ним осуществлялись в формате JSON, такой запрос можно сформировать в CURL:

$data = array( 'name' => 'snipp.ru' 'text' => 'Отправка сообщения', ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $res = curl_exec($ch); curl_close($ch);

А также могут обратится к вашим скриптам в таком формате, чтение JSON запроса.

$data = file_get_contents('php://input'); $data = json_decode($data, true);

Источник

Оцените статью