Php read write json file
I have the following JSON in a file Show
How do I add Here's what I have so far:
Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:
I'm using PHP5.2. Any thoughts? Thanks! JSON (JavaScript Object Notation) is a standard file format for data exchange between applications. In this tutorial, we will learn how to perform the most common manipulation, such as encoding, decoding, and converting JSON to Array and Array to JSON with the help of examples. We'll also discover how to read and write JSON files in PHP. Finally, we'll look at how to stream a big JSON file while using very little memory. The whole code and examples are available in a GitHub repository; it comes packaged as a simple Symfony project and provides a Docker image. JSON String ExampleIn this tutorial, we'll use the following JSON string containing a list of movies and their properties.
Convert a JSON String to an Associative Array Using json_decodeWe use The second
parameter of
The result is an array containing one associative array for each movie. The keys of each associative array are the fields of the JSON object.
Convert an Associative Array to a JSON string Using json_encodeWe use The second parameter of
The compact JSON string format:
The pretty JSON string format:
Read a JSON File in PHPWe'll use the same format here; the file
We parse the JSON file using native PHP functions:
The result:
Write a JSON File in PHPWe create and write a JSON file from an associative array:
CSV for Comma-Separated Values is another standard format to exchange data between applications, and it's pretty straightforward to convert from JSON to CSV (and from CSV to JSON). Out of Memory!When reading a large JSON file, you'll quickly encounter a memory consumption issue: "Error: Allowed memory size of X bytes exhausted". It's normal! The native methods load the entire content in memory. You can raise the Great news, there is an alternative approach; let's explore it. Stream a Big JSON FileWe use a JSON file including 500k movies records; it weights almost 300MB:
We'll install and use the
JSON Machine is an efficient PHP JSON stream parser based on generators. Read our big JSON file:
And here is the result:
Yes, we parsed our 500k JSON records in 20 seconds and using only 8MB! We can't predict how big the file to integrate will be in some cases. Using a streaming approach will make your code more robust, fast, memory-efficient, and future-proof. Download the Code and ExamplesYou can find all the code and examples in this GitHub repository. It's packaged as a simple Symfony project, a set of commands, it also comes with a Docker image. 🐋 |