Convert from json php

PHP JSON

Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.

JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.

JSON is built on two structures:

  • A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
  • An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.

The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.

PHP JSON extension

PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.

Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.

Converting PHP variables to JSON using json_encode() function

To get a JSON representation of a variable, you use the json_encode() function:

json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|falseCode language: PHP (php)

The following example uses the json_encode() function to convert an indexed array in PHP to JSON format:

 $names = ['Alice', 'Bob', 'John']; $json_data = json_encode($names); // return JSON to the browsers header('Content-type:application/json'); echo $json_data;Code language: PHP (php)
  • First, define an array of strings that consists of three elements.
  • Second, convert the array to JSON using the json_encode() function.
  • Third, return the JSON data to the browsers by setting the content type of the document to appplication/json using the header() function.
[ "Alice", "Bob", "John" ]Code language: JSON / JSON with Comments (json)

The following example uses the json_encode() function to convert an associative array in PHP to an object in JSON:

 $person = [ 'name' => 'Alice', 'age' => 20 ]; header('Content-type:application/json'); echo json_encode($person);Code language: PHP (php)
< name: "Alice", age: 20 >Code language: PHP (php)

In practice, you would select data from a database and use the json_encode() function to convert it to the JSON data.

Converting JSON data to PHP variables

To convert JSON data to a variable in PHP, you use the json_decode() function:

json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixedCode language: PHP (php)

The following example shows how to use json_decode() function to convert JSON data to a variable in PHP:

 $json_data = ''; $person = json_decode($json_data); var_dump($person);Code language: PHP (php)
object(stdClass)#1 (2) ["name"] => string(5) "Alice" ["age"] => int(20) > Code language: PHP (php)

In this example, the json_decode() function converts an object in JSON to an object in PHP. The object is an instance of the stdClass class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.

Serializing PHP objects

To serialize an object to JSON data, you need to implement the JsonSerializable interface. The JsonSerializable interface has the jsonSerialize() method that specifies the JSON representation of the object.

For example, the following shows how to implement the JsonSerializable interface and use the json_encode() function to serialize the object:

 class Person implements JsonSerializable < private $name; private $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > public function jsonSerialize() < return [ 'name' => $this->name, 'age' => $this->age ]; > > // serialize object to json $alice = new Person('Alice', 20); echo json_encode($alice);Code language: PHP (php)
"name":"Alice","age":20>Code language: PHP (php)
  • First, define a Person class that implements the JsonSerializable interface.
  • Second, return an array that consists of name and age properties from the jsonSerialize() method. The json_encode() function will use the return value of this method to create JSON data.
  • Third, create a new Person object and serialize it to JSON data using the json_encode() function.

Summary

  • JSON is a lightweight data-interchange format.
  • Use the json_encode() function to convert PHP variables to JSON.
  • Use the json_decode() function to convert JSON data to PHP variables.
  • Implement the JsonSerializable interface to specify the JSON representation of an object.

Источник

json_decode

Takes a JSON encoded string and converts it into a PHP value.

Parameters

The json string being decoded.

This function only works with UTF-8 encoded strings.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

When true , JSON objects will be returned as associative array s; when false , JSON objects will be returned as object s. When null , JSON objects will be returned as associative array s or object s depending on whether JSON_OBJECT_AS_ARRAY is set in the flags .

Maximum nesting depth of the structure being decoded. The value must be greater than 0 , and less than or equal to 2147483647 .

Bitmask of JSON_BIGINT_AS_STRING , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_OBJECT_AS_ARRAY , JSON_THROW_ON_ERROR . The behaviour of these constants is described on the JSON constants page.

Return Values

Returns the value encoded in json in appropriate PHP type. Values true , false and null are returned as true , false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.

Errors/Exceptions

If depth is outside the allowed range, a ValueError is thrown as of PHP 8.0.0, while previously, an error of level E_WARNING was raised.

Changelog

Version Description
7.3.0 JSON_THROW_ON_ERROR flags was added.
7.2.0 associative is nullable now.
7.2.0 JSON_INVALID_UTF8_IGNORE , and JSON_INVALID_UTF8_SUBSTITUTE flags were added.
7.1.0 An empty JSON key («») can be encoded to the empty object property instead of using a key with value _empty_ .

Examples

Example #1 json_decode() examples

var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , true ));

The above example will output:

object(stdClass)#1 (5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) > array(5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) >

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP’s naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

$obj = json_decode ( $json );
print $obj ->< 'foo-bar' >; // 12345

Example #3 common mistakes using json_decode()

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = «< 'bar': 'baz' >» ;
json_decode ( $bad_json ); // null

// the name must be enclosed in double quotes
$bad_json = ‘< bar: "baz" >‘ ;
json_decode ( $bad_json ); // null

// trailing commas are not allowed
$bad_json = ‘< bar: "baz", >‘ ;
json_decode ( $bad_json ); // null

Example #4 depth errors

// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode (
array(
1 => array(
‘English’ => array(
‘One’ ,
‘January’
),
‘French’ => array(
‘Une’ ,
‘Janvier’
)
)
)
);

// Show the errors for different depths.
var_dump ( json_decode ( $json , true , 4 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;

var_dump ( json_decode ( $json , true , 3 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;
?>

The above example will output:

array(1) < [1]=>array(2) < ["English"]=>array(2) < [0]=>string(3) "One" [1]=> string(7) "January" > ["French"]=> array(2) < [0]=>string(3) "Une" [1]=> string(7) "Janvier" > > > Last error: No error NULL Last error: Maximum stack depth exceeded

Example #5 json_decode() of large integers

var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , false , 512 , JSON_BIGINT_AS_STRING ));

The above example will output:

object(stdClass)#1 (1) < ["number"]=>float(1.2345678901235E+19) > object(stdClass)#1 (1) < ["number"]=>string(20) "12345678901234567890" >

Notes

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

See Also

User Contributed Notes 8 notes

JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a «list» or «object» when converted to/from JSON, depending on the keys (of absence of them).

You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:

$json = »;
$array = json_decode($json, true); // decode as associative hash
print json_encode($array) . PHP_EOL;

This will output a different JSON string than the original:

The object has turned into an array!

Similarly, a array that doesn’t have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.

$array = [
‘first’,
‘second’,
‘third’,
];
print json_encode($array) . PHP_EOL;
// remove the second element
unset($array[1]);
print json_encode($array) . PHP_EOL;

The array has turned into an object!

In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!

On the other hand, decoding/encoding from/to stdClass objects (the default) is always symmetrical.

Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.

If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use:

If you want to enforce an array to encode to a JSON object, use:

Источник

Читайте также:  Проверить существует ли массив php
Оцените статью