Json object to file php

PHP Get, Write, Read, Load, JSON Data from URL

JSON (JavaScript Object Notation) is a lightweight data interchange format that is widely used in web development. In PHP, we can easily retrieve, write, read, load JSON data from a URL using various built-in functions and libraries. In this article, you will learn how to perform these operations in PHP.

How to Get, Write, Read, Load, JSON Data from URL in PHP

  • 1. PHP read JSON file From URL
  • 2. Get JSON File Data From URL in PHP & Convert JSON to Array PHP
  • 3. Convert JSON to Object PHP
  • 4. PHP write or save JSON to a JSON file
  • Loading JSON Data from a File in PHP

1. PHP read JSON file From URL

You can use the PHP file_get_contents() function that is used to get or read or load file from the given path (Url or Source).

To get JSON data from a URL in PHP, we can use the “file_get_contents” function along with the “json_decode” function. Here’s an example:

$filename = 'data.json'; $data = file_get_contents($filename); $jsonData = json_decode($data);

In this code snippet, you first specify the filename of the JSON data that we want to read. Then, you use the “file_get_contents” function to retrieve the data from the file. Finally, you use the “json_decode” function to convert the JSON data into a PHP object.

2. Get JSON File Data From URL in PHP & Convert JSON to Array PHP

  • File get_get_conents() get that is used to get or read file from the given path (Url or Source).
  • json_decode() function of PHP, which is used to convert JSON file contents to PHP Array
$url = 'https://example.com/data.json'; $data = file_get_contents($url); $jsonData = json_decode($data);

In this code snippet, you first specify the URL of the JSON data that you want to retrieve. Then, you use the “file_get_contents” function to retrieve the data from the URL. Finally, you use the “json_decode” function to convert the JSON data into a PHP object.

3. Convert JSON to Object PHP

You can convert JSON file data to the PHP objects. You can use the json_decode() without passing the TRUE in it. Because by default, the PHP json_decode function will convert the JSON data into an object.

4. PHP write or save JSON to a JSON file

You can use the file_put_contents() function of PHP, which is used to write or save data from a given path of the JSON file or text file.

$url = 'https://example.com/data.json'; $data = array('name' => 'John Doe', 'age' => 30, 'city' => 'New York'); $jsonData = json_encode($data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response;

In this code snippet, you first specify the URL of the JSON data that we want to write to. Then, you create an array of data that you want to write to the URL and convert it into a JSON string using the “json_encode” function. Then, you use the “curl_init” function to initialize a curl session, set the request method to PUT, and set the JSON data as the request payload. Finally, you execute the curl session, retrieve the response, and close the session.

Читайте также:  Js check if string is html

5. Loading JSON Data from a File in PHP

To load JSON data from a file in PHP, we can use the “json_decode” function. Here’s an example:

$filename = 'data.json'; $data = file_get_contents($filename); $jsonData = json_decode($data);

In this code snippet, you first specify the filename of the JSON data that you want to load. Then, you use the “file_get_contents” function to retrieve the data from the file. Finally, you use the “json_decode” function to convert the JSON data into a PHP object.

Conclusion

JSON data is a popular data interchange format in web development. In PHP, you can easily retrieve, write, read, and load JSON data from a URL or a file using various built-in functions and libraries. By understanding these techniques, developers can leverage the power of JSON data in their PHP applications.

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Источник

How to Write JSON to File in PHP

Hi! In this post we’ll see how to write json to file in php. JSON formatted data is more verbose and human readable. If you want to store data which is easily processable in the future, then json format would be a preferable choice nowadays. In the past I have written several tutorials about handling json data and some of the blog readers asked for a solution to save the json data in a file. I thought writing a separate tutorial on the topic will benefit everyone. Here I have given the php script to write json formatted string to file.

php-write-json-to-file

Write JSON to File in PHP

The below php script takes up an multi-dimensional associative array, encode it into json string and then write it into a file.

 Array ( "id" => "MMZ301", "name" => "Michael Bruce", "designation" => "System Architect" ), "1" => Array ( "id" => "MMZ385", "name" => "Jennifer Winters", "designation" => "Senior Programmer" ), "2" => Array ( "id" => "MMZ593", "name" => "Donna Fox", "designation" => "Office Manager" ) ); // encode array to json $json = json_encode(array('data' => $array)); //write json to file if (file_put_contents("data.json", $json)) echo "JSON file created successfully. "; else echo "Oops! Error creating json file. "; // data.json // <"data":[<"id":"MMZ301","name":"Michael Bruce","designation":"System Architect">,,]> ?>
  • The function json_encode(array(‘data’ => $array)) encodes array to json along with a name «data».
  • The function file_put_contents(«data.json», $json) writes/stores $json string to the specified file «data.json».
  • Convert CSV File to JSON using PHP
  • Export MySQL to JSON File using PHP

Likewise you can easily write json to file in php. I hope you find this script useful. Let me know your thoughts through comments!

Источник

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:

Источник

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