Read from CSV File and Write that data in different format in txt file in PHP

Advertisements

I am reading from csv file and writing the data in txt file using the code below:

$row = 1;
$file = fopen("newfile.txt","w");

if (($handle = fopen("Last.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        $colOne = rtrim($data[0],"'");
        echo $colOne . "\n" . $data[3] . "<br />\n";
       
        $line = $colOne."_".$data[3];
        $line .=  "\n";
        fputs($file, $line);
    }
    fclose($handle);
}
fclose($file);

The fields required in the text files are obtained as needed. But I want to have a format from '000065 2022-06-01 08:06:38 to 000065_2022-06-01_08:06:38. I have tried the methods like using pre_replace(), rtrim() but was not able to achieve the desired result.

>Solution :

Use ltrim() to remove the quote from the beginning.

Use str_replace() to replace the spaces with underscores.

$colOne = str_replace(' ', '_', ltrim($data[0], "'"));

Leave a ReplyCancel reply