Super easy! Read CSV files and display them with PHP
Introduction.
To read CSV files in PHP, use the SplFileObject class in the Standard PHP Library.
Am I the only one who is excited about CSV and converting?
(No converts in this case).
Am I the only one who is excited about CSV and converting?
(No converts in this case).
treatment
It is easy to use.
It is a standard PHP class, so there is no need to install it or anything.
It is a standard PHP class, so there is no need to install it or anything.
PHP
<?php
$file = new SplFileObject('data.csv', 'r');
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);
foreach ($file as $line) {
echo $line[0];
echo $line[1];
echo $line[2];
}
predefined constant
SplFileObject::DROP_NEW_LINE---The new line at the end of a line is skipped.
SplFileObject::READ_AHEAD---Read ahead/rewind.
SplFileObject::SKIP_EMPTY---Skips reading blank lines in the file. The READ_AHEAD flag must be enabled for this to work as expected.
SplFileObject::READ_CSV ... reads a line as a CSV column.
SplFileObject::READ_AHEAD---Read ahead/rewind.
SplFileObject::SKIP_EMPTY---Skips reading blank lines in the file. The READ_AHEAD flag must be enabled for this to work as expected.
SplFileObject::READ_CSV ... reads a line as a CSV column.
demonstration
As a demonstration, I made a historical timeline.
I would like to make other periods soon.
https://history.c-blanc.com/
I would like to make other periods soon.
https://history.c-blanc.com/
data.csv
1868,慶応,4,"戊辰戦争"
1869,明治,2,"↓"
1870,明治,3,""
1871,明治,4,"廃藩置県"
1872,明治,5,""
1873,明治,6,""
1874,明治,7,""
1875,明治,8,"樺太・千島交換条約
...
At the end.
It may be useful for data that is not large enough to be used in a database.
If necessary, use nl2br for line break processing and htmlspecialchars for escaping.
You could also include a process to skip lines where the event is blank.
You can fill them all in, but are there any famous events?
Personally, I find it interesting that "Kagawa Prefecture became independent from Ehime Prefecture in 1888"...
If necessary, use nl2br for line break processing and htmlspecialchars for escaping.
You could also include a process to skip lines where the event is blank.
You can fill them all in, but are there any famous events?
Personally, I find it interesting that "Kagawa Prefecture became independent from Ehime Prefecture in 1888"...
PROFILE
- C:blanc
- I am a freelance programmer.
RECOMMEND
People who read this article also read.
COMMENT
Submitted. Comments will appear after approval.