PHP - Read CSV File & Concatenate Columns into Delimited Rows and Output into New File

Good Day All,
Trying to take a stab at bettering my PHP and reducing the amount of tedious work by automating some of my work. I'm trying to write a PHP file that takes a CSV and converts the columns into delimited rows.
Example:
12:11:00 Mark Hello
12:23:10 Jane Hi there!
12:24:32 Bob What's up?
In the output CSV, it should be one row with three columns that look like this [Delimiter is |||]:
12:11:00|||12:23:10|||12:24:32,Mark|||Jane|||Bob,Hello|||Hi there!|||What's up?
I saw similar code on here but it concatenates all into one lump and I tried to mod it to make it into three columns.
I am not the author of this code as I scraped it from a post on Stack Exchange and tried to mod it for my use case. If someone could help me with this, I would be most appreciative!
<?php
$rows = [];
$file = fopen("test.csv", "r"); // open your file
while (!feof($file)) { // read file till the end
$row = fgetcsv($file); // get current row as an array of elements
if (!empty($row)) { // check that it's not the empty row
array_push($rows, $row); // store row in array
}
}
fclose($file);
for ($r1 = 0; $r1 < count($rows); $r1++) {
echo $rows[$r1][0] . '_' . PHP_EOL;}
for ($r2 = 0; $r2 < count($rows); $r2++) {
echo $rows[$r2][1] . '_' . PHP_EOL; }
for ($r3 = 0; $r3 < count($rows); $r3++) {
echo $rows[$r3][2] . PHP_EOL;}
Answer
Solution:
<?php
$myfile = fopen("test.csv", "r") or die("Unable to open file!");
$content = fread($myfile, filesize("test.csv"));
fclose($myfile);
$times = $names = $texts = [];
foreach (explode("\n", $content) as $line) {
$words = explode(' ', $line); // separate line by spaces
$times[] = $words[0]; // first string
$names[] = $words[1]; // second string
$texts[] = implode(' ', array_splice($words, 2)); // all remaining strings
}
$output = implode('
->
', $times).','.implode('
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the browser (or proxy) sent a request that this server could not understand.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.