In our code, we define a list of books. So far, we have only three books, but you can guess that if we want to make this application useful, the list will grow way more. Storing the information inside your code is not practical at all, so we have to start thinking about externalizing it.
If we think in terms of separating the code
from the data, there is no need to keep using PHP arrays to define
the books. Using a less language-restrictive system will allow
people who do not know PHP to edit the content of the file. There
are many solutions for this, like CSV or XML files, but nowadays,
one of the most used systems to represent data in web applications
is JSON. PHP allows you to convert arrays to JSON and vice versa
using just a couple of functions: json_encode
and json_decode
. Easy, right?
Save the following into books.json
:
[ { "title": "To Kill A Mockingbird", "author": "Harper Lee", "available": true, "pages": 336, "isbn": 9780061120084 }, { "title": "1984", "author": "George Orwell", "available": true, "pages": 267, "isbn": 9780547249643 }, { "title": "One Hundred Years Of Solitude", "author": "Gabriel Garcia Marquez", "available": false, "pages": 457, "isbn": 9785267006323 } ]
The preceding code snippet is a JSON
representation of our array in PHP. Now, let's read this
information with the function file_get_contents
, and transform it to a PHP array
with json_decode
. Replace the array with
these two lines:
$booksJson = file_get_contents('books.json'); $books = json_decode($booksJson, true);
With just one function, we are able to store all the content from the JSON file
in a variable as a string. With the function, we transform this
JSON string into an array. The second argument in json_decode
tells PHP to transform it to an array,
otherwise it would use objects, which we have not covered as
yet.
When referencing files within PHP functions,
you need to know whether to use absolute or relative paths. When
using relative paths, PHP will try to find the file inside the same
directory where the PHP script is. If not found, PHP will try to
find it in other directories defined in the include_path
directive, but that is something you
would like to avoid. Instead, you could use absolute paths, which
is a way to make sure the reference will not be misunderstood.
Let's see two examples:
$booksJson = file_get_contents('/home/user/bookstore/books.json'); $booksJson = file_get_contents(__DIR__, '/books.json');
The constant __DIR__
contains the directory name of the current PHP file, and if we
prefix it to the name of our file, we will have an absolute path.
In fact, even though you might think that writing down the whole
path by yourself is better, using __DIR__
allows you to move your application anywhere
else without needing to change anything in the code, as its content
will always match the directory of the script, whereas the
hardcoded path from the first example will not be valid
anymore.