Welcome to a tutorial on how to read a CSV file into a JSON-encoded string in PHP. So you are working on a project that needs to read a CSV file, and maybe send that to an API in JSON format?
“Converting” CSV into a JSON-encoded string is a 2 steps process in PHP:
- Read the CSV file into an array first.
- JSON encode the array.
Yep, let us walk through a few simple examples – Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PHP READ CSV FILE INTO JSON
All right, let us now get into the examples of reading a CSV file into a JSON string in PHP.
EXAMPLE 1) CSV TO INDEXED ARRAY
1A) DUMMY DATA
Joe Doe | joe@doe.com |
Jon Doe | jon@doe.com |
Joy Doe | joy@doe.com |
For this example, we will be working with this simple CSV list of users.
1B) NESTED INDEXED ARRAY
<?php
// (A) EXTRACT ROWS & COLS INTO ARRAY
$data = [];
$stream = fopen("1a-dummy.csv", "r");
while (($row = fgetcsv($stream)) !== false) { array_push($data, $row); }
fclose($stream);
// (B) JSON ENCODE DATA
print_r($data);
echo json_encode($data);
[["Joe Doe","joe@doe.com"],["Jon Doe","jon@doe.com"],["Joy Doe","joy@doe.com"]]
- Create an empty array
$data = []
. - Read the CSV file, use
array_push()
to collect all the data into$data
. - Lastly,
json_encode($data)
.
Sorry to those who are expecting more, but that’s all. 😆
1C) FLAT INDEXED ARRAY
<?php
// (A) EXTRACT ROWS & COLS INTO ARRAY
$data = [];
$stream = fopen("1a-dummy.csv", "r");
while (($row = fgetcsv($stream)) !== false) { array_push($data, ...$row); }
fclose($stream);
// (B) JSON ENCODE DATA
print_r($data);
echo json_encode($data);
["Joe Doe","joe@doe.com","Jon Doe","jon@doe.com","Joy Doe","joy@doe.com"]
If you prefer a flat array of values, just spread the values ...$row
when collecting the data.
EXAMPLE 2) CSV TO ASSOCIATIVE ARRAY
2A) DUMMY DATA
NAME | |
Joe Doe | joe@doe.com |
Jon Doe | jon@doe.com |
Joy Doe | joy@doe.com |
For this example, the first row of the CSV file is the header.
2B) SINGLE KEY WITH MULTIPLE VALUES
<?php
// (A) FLAGS & EMPTY ARRAY
$first = true;
$keys = [];
$data = [];
// (B) EXTRACT ROWS & COLS INTO ARRAY
$stream = fopen("2a-dummy.csv", "r");
while (($row = fgetcsv($stream)) !== false) {
// (B1) FIRST ROW IS THE HEADER
if ($first) {
foreach ($row as $i=>$col) {
$keys[] = $col;
$data[$col] = [];
}
$first = false;
}
// (B2) FOLLOWING ROWS ARE DATA
else {
foreach ($row as $i=>$col) { $data[$keys[$i]][] = $col; }
}
}
fclose($stream);
// (C) JSON ENCODE DATA
print_r($keys);
print_r($data);
echo json_encode($data);
{"NAME":["Joe Doe","Jon Doe","Joy Doe"],"EMAIL":["joe@doe.com","jon@doe.com","joy@doe.com"]}
Not going to explain line by line, it’s just a matter of how you want to arrange $data
. For those who are lost, this is arranged in the format:
$data["NAME"] = [NAME, NAME, ...]
$data["EMAIL"] = [EMAIL, EMAIL, ...]
2C) NESTED INDEXED ARRAY
<?php
// (A) FLAGS & EMPTY ARRAY
$first = true;
$keys;
$data = [];
// (B) EXTRACT ROWS & COLS INTO ARRAY
$stream = fopen("2a-dummy.csv", "r");
while (($row = fgetcsv($stream)) !== false) {
// (B1) FIRST ROW IS THE HEADER
if ($first) {
$keys = $row;
$first = false;
}
// (B2) FOLLOWING ROWS ARE DATA
else {
$r = [];
foreach ($keys as $i=>$key) { $r[$key] = $row[$i]; }
$data[] = $r;
}
}
fclose($stream);
// (C) JSON ENCODE DATA
print_r($keys);
print_r($data);
echo json_encode($data);
[{"NAME":"Joe Doe","EMAIL":"joe@doe.com"},{"NAME":"Jon Doe","EMAIL":"jon@doe.com"},{"NAME":"Joy Doe","EMAIL":"joy@doe.com"}]
A final example, this is arranged in:
$data[0] = ["NAME"=>NAME, "EMAIL"=>EMAIL]
$data[1] = ["NAME"=>NAME, "EMAIL"=>EMAIL]
$data[N] = ["NAME"=>NAME, "EMAIL"=>EMAIL]
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- Display CSV As Table In PHP – Code Boxx
- Ways To Read Files In PHP – Code Boxx
- fgetcsv – Official PHP Manual
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!