Parsing CSV file using callbacks into new CSV file with changed data and header.
- PHP >= 7.1
- Copy
parse.example.php
toparse.php
:cp parse.example.php parse.php # and edit script parse.php for your purpose
- In
parse.php
can be used three callback functions (seeparse.example.php
) for parsing CSV file:- Every row (
rowCallback
) - Header (
headCallback
) - Whole result (
resultCallback
)
- Every row (
- Run php script:
php parse.php # generate new result.csv file
Will generate new CSV file: data/result.csv
file from the input file data/input.csv
,
where input.csv
and result.csv
- CSV filenames (set in the configuration array $config
).
To get the result of parsing a CSV file do not include or just comment result
param in the config:
<?php
use mrwadson\Process;
require_once __DIR__ . '/autoload.php';
$config = [
'input' => __DIR__ . '/data/input.csv',
// 'result' => __DIR__ . '/data/result.csv',
'first_row_is_header' => true, # parse first row as header
'include_header_in_result' => false # don't include header row in result
];
$result = Process::init($config)();
print_r($result);
In this case, the result file will not be written.
For every new project just copy parse.example.php
to parse-my-project.php
and use it for your purpose.
cp parse.example.php parse-my-project.php
mkdir data/my-project # create dir for the config files (see section bellow)
And just run your parse php file:
php parse-my-project.php # will process input file from the $config['input']
Where is my-project
- custom name of the project.
Or (for automatize) use prompted shell script:
read -p "Enter project name: " project_name && \
cp parse.example.php parse-$project_name.php && mkdir data/$project_name && \
sed -i "s#/data/#/data/$project_name/#" parse-$project_name.php
Configuration parameters are set in the array (in the $config
variable) directly in the parse.php
file.
There are:
input
- CSV file for parsingresult
- output result CSV file after parsingfirst_row_is_header
- the first line is the headerinclude_header_in_result
- include/exclude the header in the result CSV file (only iffirst_row_is_header
istrue
)
If you're working with multiple files best way to create a directory inside in the data
directory. So your input and result files
will be located by example at data/my-project/input.csv
and data/my-project/result.csv
files.
You can use Helper class for filtering and checking data. For example, to check and filter for some bad words use like this:
$result = Helper::matchBadWords(['some', 'bad', 'word'], 'this sentence has a bad word');
// result = 2
Or check if passed value is URL:
$result = Helper::isUrl('https://google.com'); // result = 1
$result = Helper::isUrl('google.com'); // result = 0
For more details, please see Helper class.